ENH: reproducible Monte Carlo via per-simulation-index seeding#1054
ENH: reproducible Monte Carlo via per-simulation-index seeding#1054thc1006 wants to merge 3 commits into
Conversation
Codecov Report❌ Patch coverage is
Additional details and impacted files@@ Coverage Diff @@
## develop #1054 +/- ##
===========================================
+ Coverage 81.74% 82.30% +0.56%
===========================================
Files 118 118
Lines 15248 15262 +14
===========================================
+ Hits 12464 12561 +97
+ Misses 2784 2701 -83 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
|
Pushed 0d37ed6 to cover the seeding code that the earlier tests only reached through a full (slow) Monte Carlo run.
That takes the patch from 21 uncovered lines down to 4, all in the parallel branch. I looked into whether it is worth covering those too, and I do not think it is:
So un-slowing the parallel test would recover at most the three main-process lines and still not the subprocess one, at the cost of forking workers in the default suite. I kept it |
0d37ed6 to
761c092
Compare
phmbressan
left a comment
There was a problem hiding this comment.
The implementation is very clear and throughout, nice work.
The explanation on the concepts behind per index seeding (both in the issue and PR description) were rather helpful. I agree having reproducible results was an issue with the parallel per worker seeding.
Regarding the decisions on parameter naming, I agree with most of the decisions taken here. Moreover, the rng attribute is well docstringed, so it shouldn't be a matter of confusion to the user.
@MateusStano could you give your two cents on the changes here before we proceed with a merge?
| rocket=rocket, | ||
| flight=flight, | ||
| ) | ||
| montecarlo.simulate(**simulate_kwargs) |
There was a problem hiding this comment.
Could you double check if after running this test, no files are left dangling on the test file system. If that is the case, using a try-finally block to remove those (as done in a few other MonteCarlo tests) is an option.
There was a problem hiding this comment.
Thanks for the review. On the dangling files: I checked, and nothing gets left behind. The test passes filename=tmp_path / tag into MonteCarlo, so the .inputs.txt, .outputs.txt and .errors.txt all land under pytest's per-test tmp_path and get cleaned up with it. I reran it and confirmed the repo and working directory stay clean, so there's nothing here for a try/finally to remove.
The other MonteCarlo tests need that cleanup because their fixture uses a fixed filename="monte_carlo_test", which writes into the cwd. This one keeps everything inside tmp_path instead. I'm happy to match the try/finally style if you'd prefer consistency across the file, but the tmp_path route seemed cleaner to me. Your call.
| while sim_monitor.keep_simulating(): | ||
| sim_idx = sim_monitor.increment() - 1 | ||
| inputs_json, outputs_json = "", "" | ||
|
|
||
| self.__seed_simulation(child_seeds[sim_idx]) | ||
| flight = self.__run_single_simulation() | ||
| inputs_json = self.__evaluate_flight_inputs(sim_idx) | ||
| outputs_json = self.__evaluate_flight_outputs(flight, sim_idx) |
There was a problem hiding this comment.
I am not sure about this so @thc1006 could you verify, please?
But I believe adding this child_seeds[sim_idx] can break at the very end of the simulation. If you are running 8 simulations, and we are at step 7. We could have one worker check 7<8 -> yes, and a second worker also check 7<8 -> yes, because keep_simulating() and increment() are two separate steps and nothing locks them together. Then both workers increment: the first gets sim_idx = 7 (ok), but the second gets sim_idx = 8. Since child_seeds only has 8 item, child_seeds[8] does not exist
I think this race was already there before, but it didnt crash the simulation. Could you check and fix, please?
There was a problem hiding this comment.
You're right, this is a real race. keep_simulating() and increment() are separate manager calls, so near the end multiple workers can pass the count < n check before any of them increments and then claim sim_idx == n, which the new child_seeds[sim_idx] lookup turned into an IndexError (before, it just wrote an extra record). Fixed in 9c020b6: the claim now goes through a small _claim_next_index helper that holds the shared mutex across the check and the increment, so each index is handed out once and the counter never runs past number_of_simulations. There's a deterministic unit test for it (a barrier plus a widened check-to-increment window) that over-claims and fails if the lock is removed. Thanks for catching it.
| def __seed_simulation(self, child_seed): | ||
| """Reseed the stochastic models for a single simulation index. | ||
|
|
||
| The per-index child seed is split three ways so the environment, | ||
| rocket and flight draw from independent streams instead of sharing | ||
| one. Seeding per simulation index (not per worker) is what makes the | ||
| sampled inputs invariant to the execution mode and to the number of | ||
| workers. | ||
| """ | ||
| env_seed, rocket_seed, flight_seed = child_seed.spawn(3) | ||
| self.environment._set_stochastic(env_seed) | ||
| self.rocket._set_stochastic(rocket_seed) | ||
| self.flight._set_stochastic(flight_seed) |
There was a problem hiding this comment.
This .spawn() call seems to make the case of using SeedSequence/Generator not repeatable
From what I understand if a user builds a SeedSequence (or Generator) once and passes the same object to simulate() twice, the first will spawns a set of children and the second run will spawn another set
There was a problem hiding this comment.
Agreed, the current code mutated the caller's seed lineage. SeedSequence.spawn() advances n_children_spawned, and the helper returned the original object, so a second simulate() with the same object spawned a different set. Fixed in 9c020b6 with two changes:
- A supplied
SeedSequenceis now copied from its fullstate(entropy, spawn_key, pool_size, n_children_spawned) before spawning, so the caller's object is untouched and repeated calls reproduce the same children. Copying onlyentropywould dropspawn_key, which matters for a spawned child. - I dropped
Generator/BitGeneratorfrom the accepted types. A generator is a stateful RNG, not a seed: itsbit_generator.seed_seqis only the original lineage, so a generator advanced by a million draws would still seed the run identically to a fresh one. SPEC 7'srngsemantics would instead consume it, the opposite of a reproducible seed.random_seednow takes an int, a sequence of ints, or aSeedSequence; a generator user can passrng.bit_generator.seed_seq.
Tests cover the same-object reproducibility, n_children_spawned staying put, a spawned child with a non-empty spawn_key, and the generator rejection.
Addresses review feedback on RocketPy-Team#1054. Parallel workers claimed the next index with an unlocked keep_simulating() + increment(), so near the end of a run two workers could both pass the count < n check and then claim sim_idx == n; the per-index child_seeds lookup turned that into an IndexError (before, it only wrote one extra record). Move the claim into a _claim_next_index helper that holds the shared mutex across the check and the increment, so each index is handed out once and the counter never overshoots. A deterministic unit test (a barrier plus a widened check-to-increment window) over-claims and fails if the lock is dropped. __root_seed_sequence returned the caller's SeedSequence, and spawn() advances its child counter, so passing the same object to simulate() twice produced different children. Copy it from its full state instead, which leaves the caller untouched and keeps repeated calls reproducible. Also drop Generator/BitGenerator from the accepted types: a stateful generator is not a seed, and reducing it to its underlying SeedSequence ignores how far it has been consumed. random_seed now takes an int, a sequence of ints, or a SeedSequence. Signed-off-by: thc1006 <84045975+thc1006@users.noreply.github.com>
MonteCarlo seeded the stochastic models per worker in parallel mode (from a fresh, unseeded SeedSequence) and once at construction in serial mode, so the sampled inputs depended on the execution mode and the worker count, and parallel runs were not reproducible run to run. Add a keyword-only random_seed to simulate() (SPEC 7 style: accepts an int, a SeedSequence, or a Generator; None keeps the previous fresh-entropy behavior). Spawn one child seed per simulation index from that root and reseed the stochastic models from child_seeds[i] before simulation i. SeedSequence.spawn is prefix-stable, so index i maps to the same seed regardless of which worker runs it, making the inputs identical across serial, parallel(2) and parallel(N). Each index seed is split three ways so the environment, rocket and flight draw from independent streams rather than sharing one. The serial index field now counts from 0 to match the parallel path. Both changes alter the numbers a fixed seed produces, so stored baselines regenerate. Adds tests/unit/simulation/test_monte_carlo_determinism.py: serial reproducibility, worker invariance (serial == parallel(2) == parallel(4)), and the None-seed path. Signed-off-by: thc1006 <84045975+thc1006@users.noreply.github.com>
The reproducible-seeding change added __root_seed_sequence and __seed_simulation plus the per-index serial and parallel seeding, but the only tests that reached them ran a full Monte Carlo and were marked slow, so the coverage job (which does not pass --runslow) never executed them. Add fast unit tests that drive the two helpers directly: every supported random_seed type normalizes to the same root stream, None draws fresh entropy, existing SeedSequence/Generator/BitGenerator objects are reused rather than copied, and each child seed splits three ways so environment, rocket and flight get independent streams. Move the end-to-end simulate reproducibility tests into tests/integration, next to the existing Monte Carlo simulate test. The serial reproducibility run now lives in the non-slow suite; only the fork-based worker-invariance test stays slow, and it imports multiprocess lazily like the library does. Signed-off-by: thc1006 <84045975+thc1006@users.noreply.github.com>
Addresses review feedback on RocketPy-Team#1054. Parallel workers claimed the next index with an unlocked keep_simulating() + increment(), so near the end of a run two workers could both pass the count < n check and then claim sim_idx == n; the per-index child_seeds lookup turned that into an IndexError (before, it only wrote one extra record). Move the claim into a _claim_next_index helper that holds the shared mutex across the check and the increment, so each index is handed out once and the counter never overshoots. A deterministic unit test (a barrier plus a widened check-to-increment window) over-claims and fails if the lock is dropped. __root_seed_sequence returned the caller's SeedSequence, and spawn() advances its child counter, so passing the same object to simulate() twice produced different children. Copy it from its full state instead, which leaves the caller untouched and keeps repeated calls reproducible. Also drop Generator/BitGenerator from the accepted types: a stateful generator is not a seed, and reducing it to its underlying SeedSequence ignores how far it has been consumed. random_seed now takes an int, a sequence of ints, or a SeedSequence. Signed-off-by: thc1006 <84045975+thc1006@users.noreply.github.com>
9c020b6 to
3e22729
Compare
Pull request type
Current behavior
MonteCarlo.simulate()seeds the stochastic models per worker in parallel mode (from a fresh, unseedednp.random.SeedSequence().spawn(n_workers)) and once at construction in serial mode. So the sampled inputs depend on the execution mode and the number of workers, and parallel runs aren't reproducible run to run. This is #1053.New behavior
Adds a keyword-only
random_seedtosimulate(). From that root I spawn one child seed per simulation index and reseed the models fromchild_seeds[i]before simulationi.SeedSequence.spawnis prefix-stable, so indeximaps to the same seed regardless of which worker runs it. The sampled inputs come out identical across serial, parallel(2) and parallel(N), and reproducible from the seed.random_seedis a seed, not a live RNG: it takes an int, a sequence of ints, or aSeedSequence, withNone= fresh entropy so existing behavior is unchanged unless you pass a seed. A suppliedSeedSequenceis copied from its full state before spawning, so it is never mutated and repeated calls with the same object reproduce the same run. This is informed by SPEC 7 (a per-call keyword-only seed) and NumPy's parallel idiom (SeedSequence(root).spawn(n)), but it keeps seed-snapshot semantics rather than SPEC 7's statefulrng: aGenerator/BitGeneratoris not accepted, because reducing it to its underlyingSeedSequencewould ignore how far it has been consumed. Passrng.bit_generator.seed_seqto seed from an existing generator.Tests
tests/unit/simulation/test_monte_carlo_determinism.pyunit-tests the seed handling (the accepted seed types, theSeedSequencecopy leaving the caller untouched, the three-way env/rocket/flight split) and the parallel index claim (a deterministic barrier-based test that fails if the claim's lock is dropped).tests/integration/simulation/test_monte_carlo_determinism.pycovers end-to-end reproducibility (serial, and serial == parallel(2) == parallel(4)) with a stubbedFlight.Notes from review
keep_simulating()+increment(). Near the end of a run two workers could both passcount < nand then claimsim_idx == n, and the per-indexchild_seedslookup turned that into anIndexError. The claim now holds the shared mutex across the check and the increment, so each index is handed out once.SeedSequencewas returned as-is, andspawn()advances its child counter, so passing the same object twice was not reproducible. It is now copied from its full state, andGenerator/BitGeneratorare no longer accepted (see above).Known limitation
From #1053: list-valued stochastic attributes are sampled with the stdlib
random.choice(an unseeded global), so a model with a multi-elementthrust_sourceisn't fully seed-controlled yet. A full fix would seed the stdlibrandomper index too.Breaking change
The exact numbers a run produces change (per-index seeding, the env/rocket/flight decorrelation, and the serial index now counting from 0 to match parallel), so external code that pinned exact Monte Carlo samples would need to re-baseline. The in-repo Monte Carlo tests don't pin exact values (
test_monte_carlo_simulatechecks apogee and impact velocity within a tolerance), so none of them change. There's no API break for users who don't pin exact samples, andrandom_seedis opt-in.One more heads-up: Python 3.14 flipped the Linux multiprocessing default from fork to forkserver, so workers no longer inherit memory and the seed objects crossing the process boundary must be picklable.
SeedSequenceis, and the tests pass under fork.Closes #1053