⚡️ Speed up method LocalInteraction._play by 76%#116
Open
codeflash-ai[bot] wants to merge 1 commit intomainfrom
Open
⚡️ Speed up method LocalInteraction._play by 76%#116codeflash-ai[bot] wants to merge 1 commit intomainfrom
LocalInteraction._play by 76%#116codeflash-ai[bot] wants to merge 1 commit intomainfrom
Conversation
The optimized code achieves a **76% speedup** (15.1ms → 8.54ms) by introducing a fast path for the most common case in the `LocalInteraction._play` method.
## Key Optimization
**Vectorized Best Response Computation**: When `tie_breaking='smallest'` (the default and most common case), the optimization replaces individual `Player.best_response()` calls in a loop with a single vectorized matrix operation:
```python
# Original: Loop calling best_response for each player
for k, i in enumerate(player_ind):
actions[i] = self.players[i].best_response(
opponent_act_dict[k, :], tie_breaking=tie_breaking, ...
)
# Optimized: Single vectorized computation
actions_onehot = np.eye(self.num_actions, dtype=int)[np.asarray(actions)]
opponent_act_dict = self.adj_matrix[player_ind].dot(actions_onehot)
payoffs = payoff_matrix @ opponent_act_dict.T
best_indices = (payoffs >= (max_vals - tol)).argmax(axis=0)
```
## Why This Is Faster
1. **Batch Processing**: Computes payoffs for all players simultaneously using NumPy's efficient matrix operations instead of Python-level loops
2. **Reduced Function Call Overhead**: Eliminates repeated calls to `best_response()`, `payoff_vector()`, and sparse matrix operations inside the loop
3. **Memory Access Patterns**: Better cache locality from contiguous array operations versus scattered method calls
## Test Results Analysis
The optimization shows **dramatic improvements** (54-485% faster) across nearly all test cases:
- **Small networks** (2-3 players): 55-79% faster
- **Medium networks** (30-50 players): 125-189% faster
- **Large networks** (100+ players): 221-485% faster
The speedup scales with network size because the vectorization benefit compounds with more players. Tests with `tie_breaking='random'` show no regression (~1ms, unchanged) since they use the original fallback path.
## Impact Considerations
The fast path only activates when `tie_breaking='smallest'`, which is the **default parameter** in the `LocalInteraction` class definition. This means most existing workloads automatically benefit without code changes. Workloads involving simulations with many iterations (common in game theory research) will see substantial cumulative time savings.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.
📄 76% (0.76x) speedup for
LocalInteraction._playinquantecon/game_theory/localint.py⏱️ Runtime :
15.1 milliseconds→8.54 milliseconds(best of138runs)📝 Explanation and details
The optimized code achieves a 76% speedup (15.1ms → 8.54ms) by introducing a fast path for the most common case in the
LocalInteraction._playmethod.Key Optimization
Vectorized Best Response Computation: When
tie_breaking='smallest'(the default and most common case), the optimization replaces individualPlayer.best_response()calls in a loop with a single vectorized matrix operation:Why This Is Faster
best_response(),payoff_vector(), and sparse matrix operations inside the loopTest Results Analysis
The optimization shows dramatic improvements (54-485% faster) across nearly all test cases:
The speedup scales with network size because the vectorization benefit compounds with more players. Tests with
tie_breaking='random'show no regression (~1ms, unchanged) since they use the original fallback path.Impact Considerations
The fast path only activates when
tie_breaking='smallest', which is the default parameter in theLocalInteractionclass definition. This means most existing workloads automatically benefit without code changes. Workloads involving simulations with many iterations (common in game theory research) will see substantial cumulative time savings.✅ Correctness verification report:
🌀 Click to see Generated Regression Tests
To edit these changes
git checkout codeflash/optimize-LocalInteraction._play-mkp7brrnand push.