⚡️ Speed up method DiscreteDP.evaluate_policy by 28%
#74
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
📄 28% (0.28x) speedup for
DiscreteDP.evaluate_policyinquantecon/markov/ddp.py⏱️ Runtime :
4.60 milliseconds→3.58 milliseconds(best of110runs)📝 Explanation and details
The optimized code achieves a 28% speedup by introducing Numba JIT compilation to accelerate key computational bottlenecks in the
RQ_sigmaandevaluate_policymethods.Key Optimizations
1. Numba-accelerated indexing operations
Three JIT-compiled functions replace Python/NumPy indexing:
_rq_sigma_sa_pair_numba: Replaces the call to_find_indicesfollowed by array indexing for state-action pair formulation. This eliminates Python overhead in the index lookup loop and subsequent fancy indexing operations._rq_sigma_regular_numba: Replaces fancy indexingR[np.arange(num_states), sigma]andQ[np.arange(num_states), sigma]with explicit loops. While NumPy's fancy indexing involves overhead for index validation and temporary array creation, Numba's JIT compilation produces optimized machine code that directly accesses memory locations._I_minus_beta_Q_sigma: JIT-compiles the matrix subtraction operationI - beta * Q_sigma, converting the Python/NumPy operation into compiled code with eliminated interpreter overhead.2. Why this leads to speedup
For dense arrays (non-sparse case):
_find_indicestaking ~79% of time inRQ_sigma(6.37ms out of 8.05ms)For matrix operations:
I - beta * Q_sigmaoperation, while only 15.1% of runtime, benefits from Numba's compiled arithmetic, especially visible in the 61.6% speedup on the large-scale performance test (300 states)3. Impact on workloads
The optimization particularly benefits:
The optimization has minimal impact on sparse matrices (0.7-1.5% slower), as scipy.sparse operations are already optimized and cannot be accelerated by Numba, so those code paths fall back to the original implementation.
4. Test case performance patterns
✅ Correctness verification report:
🌀 Click to see Generated Regression Tests
To edit these changes
git checkout codeflash/optimize-DiscreteDP.evaluate_policy-mjw2ak48and push.