Refactor cross-section simulation: reverse loop structure for better performance #734
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.
Summary
This PR refactors the cross-sectional agent simulation in both McCall model lectures to use a more efficient and modular loop structure.
Key Changes
Previous approach: Loop over time steps, vectorize over all agents at each step
New approach: Vectorize over agents, with each agent looping over time internally
Implementation Details
sim_agent()function - Useslax.fori_loopto simulate a single agent forward T time steps withfold_infor key generationsim_agents_vmap- Vectorizessim_agentacross multiple agents usingjax.vmapsimulate_cross_section()- Now generates n_agents keys and passes each tosim_agentplot_cross_sectional_unemployment()- Usessim_agents_vmapdirectlysimulate_employment_path()(records full history for visualization) andsim_agent()(returns only final state for efficiency)Performance
Testing with 50,000 agents over 200 periods showed:
@jax.jitonsim_agent: New approach is ~1.07x faster and has lower varianceFiles Modified
mccall_model_with_sep_markov.md(discrete wage case)mccall_fitted_vfi.md(continuous wage case)Both files now use the same efficient pattern, with the only difference being continuous vs discrete wages.
Testing
Both notebooks have been converted to Python and run successfully, producing expected results that match the ergodic theorem (time-average ≈ cross-sectional average).
🤖 Generated with Claude Code