⚡️ Speed up method DiscreteDP.to_sa_pair_form by 14%
#71
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.
📄 14% (0.14x) speedup for
DiscreteDP.to_sa_pair_forminquantecon/markov/ddp.py⏱️ Runtime :
1.78 milliseconds→1.56 milliseconds(best of70runs)📝 Explanation and details
The optimized code achieves a 14% speedup by replacing pure-Python state-wise maximization logic with Numba JIT-compiled functions (
_numba_s_wise_maxand_numba_s_wise_max_argmax) in the SA-pair branch of theDiscreteDP.__init__method.What changed:
_s_wise_maxand_s_wise_max_argmax).s_wise_maxclosure in the_sa_pair=Truebranch now calls these Numba functions instead of the original Cython implementations._check_action_feasibilitymethod was explicitly defined (previously it was called but not shown in the original code).Why it's faster:
Numba's JIT compilation produces machine code that eliminates Python interpreter overhead for tight loops. The explicit loop structure in
_numba_s_wise_maxand_numba_s_wise_max_argmaxallows Numba to:The SA-pair representation is common in discrete dynamic programming for sparse action spaces, so this optimization targets a hot path in Markov decision process solvers.
Test case performance:
test_basic_small_dense_to_sa_pair_sparse: 11.3% faster,test_large_all_feasible_dense_to_sa_pair_dense: 20.3% faster)test_basic_already_sa_pair_returns_self: 25.6% faster)Impact on existing workloads:
The
to_sa_pair_formmethod is a preprocessing step typically called once during model initialization. While the 14% speedup is valuable, the primary benefit comes from the Numba-optimizeds_wise_maxfunction being used in downstream iterative solvers (value iteration, policy iteration) where it's called hundreds of times, though those methods aren't shown in this profile.✅ Correctness verification report:
🌀 Click to see Generated Regression Tests
To edit these changes
git checkout codeflash/optimize-DiscreteDP.to_sa_pair_form-mjw0qn25and push.