Skip to content

feat: A4b search-level seed (SeedSequence fan-out, conditional identifier walk, legacy table) - #1686

Merged
Jammy2211 merged 8 commits into
mainfrom
feature/search-ext-a4-seed
Oct 14, 2026
Merged

Jammy2211 merged 8 commits into
mainfrom
feature/search-ext-a4-seed

Conversation

@Jammy2211

@Jammy2211 Jammy2211 commented Oct 14, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

Search-extensibility phase A4b (PR 2 of 3, stacked on #1685; base feature/search-ext-a4-decompose). This adds one search-level seed (decision D4), fanned out with numpy.random.SeedSequence. The seed enters the identifier through a conditional in the identifier walk, never through the base __identifier_fields__. Issue #1684 is closed by PR 3.

What changed, by sub-step

  1. Base seed + fan-out + identifier (2954b09a0). NonLinearSearch.__init__(..., seed=None). autofit/non_linear/search/seed.py holds the rules:

    • stream 0 → the initializer (start_points passes initializer_rng(search));
    • FitContext.rng spawns stream 0 on construction, so the backend's ctx.rng.spawn(k) gets streams 1..k;
    • legacy _fit backends use backend_seed_sequences / backend_random_state / backend_generator;
    • grid-search jobs set _seed_spawn_key = (index,), which gives independent child streams and is neither serialized nor hashed.

    autofit/mapper/identifier.py appends seed after the __identifier_fields__ values only when type(value)._identifier_seed exists, "seed" is not already a field, and the seed is not None. docs/design/run_ctx.md gains Revision 3.

  2. Initializer off global random (f4f23aa8c). AbstractInitializer.samples_from_model(..., rng=None). Every draw (Initializer, InitializerParamBounds, InitializerParamStartPoints fallbacks) uses the passed numpy.random.Generator, or a fresh unseeded one, through initializer.rng.

  3. Legacy table + seeded backends (2b3536f62):

    Search Rule now vs main
    Nautilus, NSS "seed" stays a static field; their seed kwarg is passed to the base (alias) identifiers, hash_lists and backend seeding unchanged
    BlackJAXNUTS, SMC seed=None default → backend_seed == 42, unhashed; a user-supplied seed (incl. 42) is hashed default unchanged; explicit-seed folders re-key (accepted)
    the other 11 hashed only when not None default unchanged

    Emcee's RandomState and dynesty's rstate come from backend stream 1 when a seed is given (unseeded runs keep each backend's own default). Nautilus (Sampler(seed=)), NSS/NUTS/SMC (PRNGKey) and MultiStart (SeedSequence([seed, stream])) keep taking the seed directly, so existing seeded runs of those reproduce exactly.

  4. Tests (27e77474c): test_seed.py with seed_golden.json, which holds main 8437a3b's values plus the new explicit-seed identifiers.

Invariants

# Invariant Evidence
1 Public names unchanged
2 Identifier hashes the A0a golden table passes unchanged. default and explicit-None identifiers and hash_lists for all 15 are byte-identical to main (test_default_and_explicit_none_identifiers_unchanged, test_default_hash_list_unchanged; Nautilus().hash_list included). The only changes are the seed table's own, listed under "Accepted re-keys"
3 search.json, constructor arguments round-trip passes for all 15. Constructor signatures are unchanged by name (the golden constructor_arguments pass). The serialized argument set gains one key, seed (null unless passed), for every search, because dictable walks the base __init__; test_dict.py's fixture records it. Old JSON without seed loads
4 On-disk layout old-incomplete-output: a default-constructed search, and a seeded Nautilus/NSS, resolve the same output-path identifier as main for a model (test_old_incomplete_output_resolves_the_same_folder)
5 samples_info["class_path"] unchanged
6 Clipper tripwire passes
7–9 unchanged

Accepted re-keys (for the human reviewer)

  • BlackJAXNUTS / SMC with an explicit seed (including seed=42). These now hash the seed, so existing explicit-seed output folders re-key, as accepted in the epic report §8.6.
  • Old JSON of default BlackJAXNUTS / SMC. main recorded seed: 42 in search.json. Loading it passes 42 explicitly, so the loaded object hashes it. Output folders are not recomputed from search.json (identifiers are on disk), so nothing re-keys on disk; the test pins this behaviour.
  • ⚠️ MultiStart{Adam,ADABelief,Lion,Prodigy} with an explicit seed. The legacy table lists them under "the other 11 … no seed", but they already had an unhashed seed argument (it seeds _broad_starts / resurrection). Applying the table's "hashed only when not None" rule therefore re-keys existing explicit-seed MultiStart folders. Their sampling is bit-identical: _seed_for is untouched. This is within the seed table's rule but was not anticipated by the report. Please confirm it on review. The alternative is one line: keep MultiStart's seed unhashed by overriding _identifier_seed to return None.

Witness

  • Same seed → identical initial points for every one of the 15 searches (test_same_seed_same_initial_points, through start_points), and different seeds give different points. The initializer never touches the global random module (test_initializer_never_uses_the_global_random_module).
  • Two Emcee(seed=1) fits on this machine write byte-identical samples.csv (test_two_seeded_emcee_fits_write_identical_samples). The control is two unseeded fits, which differ.
  • Nautilus().hash_list is unchanged.
  • The golden table is byte-identical for all 15 default constructions. The explicit-None, explicit-seed, old-JSON and old-incomplete-output cases are each tested separately.
  • Also covered: ctx.rng.spawn(1) equals backend stream 1, grid children get distinct streams with an unchanged identifier and no serialized spawn key, and the dynesty rstate is reproducible.

Tests

  • Full suite, serial: 3703 passed, 1 skipped, 4 xfailed (+100 over PR 1).
  • unittest-nojax emulation: 3392 passed, 176 skipped, 2 xfailed. NSS seed cases skip without blackjax.
  • Sphinx: 30 warnings. _generate_searches.py --check: up to date.
  • Workspace smoke: run on PR 3, which contains this PR.

Decisions taken

  • The NUTS/SMC sentinel is None. The signature default is None, the backend uses backend_seed = 42, and search.seed reads None by default (main read 42). A new search.json records seed: null for a default NUTS/SMC, so it reloads unhashed. An explicit seed=None (which crashed PRNGKey on main) now means the default.
  • Promise scoped honestly. Same seed gives the same initial points for every search. Bit-identical samples are demonstrated for Emcee on one platform. Zeus draws from numpy's global RNG inside its moves, so only its initial points are seeded. MCMC archive searches resume statistically.
  • Unseeded draws are not reproducible. With seed=None the initializer uses a fresh OS-entropy generator. A user who seeded the global random module to reproduce start points must now pass seed=.
  • Grid children share the hashed seed and differ only by spawn key, so child identifiers and folders are unchanged. Backends that take the raw seed (Nautilus, NSS, NUTS, SMC) see the same raw seed in every child.
  • Commit 1 references the initializer's rng argument added in commit 2. The branch head is consistent; the intermediate commit is not separately runnable.

Companion changes required

  1. autofit_workspace_test/scripts/graphical/analytic_autofit.py. This change is recommended. It is no longer required, because finding 2's precedence fix keeps the existing helper working (verified: analytic_gaussian.py passes 41/41 unchanged).
    • Delete class SeededDynestyStatic(af.DynestyStatic) (lines 206–219). It seeds dynesty by injecting rstate into search_kwargs.
    • In run_joint_fit (line 231), replace
          search = SeededDynestyStatic(
              path_prefix="graphical", name=name, seed=seed, **kwargs
          )
      with the supported search-level seed, which seeds dynesty's rstate (backend stream 1) and the initializer's live points:
          search = af.DynestyStatic(path_prefix="graphical", name=name, seed=seed, **kwargs)
    • In its docstring (line 226), replace "random and numpy.random are seeded too, for the initializer's live-point draws." with "The search-level seed seeds the initializer's live points and dynesty's rstate."
    • In scripts/graphical/analytic_gaussian.py lines 50–51, replace "(analytic_autofit.SeededDynestyStatic, dynesty rstate plus random / numpy.random for the initializer, seed 0)" with "(af.DynestyStatic(seed=0): the search-level seed seeds dynesty's rstate and the initializer)".
    • With this edit applied in a scratch copy, analytic_gaussian.py passes PARITY: PASS (41/41), 23/23 cells, exit 0. The joint-fit column values move slightly because rstate now comes from backend stream 1, not default_rng(0).

Adversary review 07 (Codex gpt-6-astra) — enacted

Each finding was reproduced first as a failing test on the pre-fix head 27e77474c (20 failures across the three findings), then fixed. One commit per finding: 5cc906af2 (finding 2), 71b925b3f (finding 1), 175d91a58 (finding 3).

# Finding Reproduced Fix Tests
1 (P1) Old default NUTS/SMC search.json and pickles record seed: 42, which PR 2 hydrated as a user seed and hashed. As a result, SearchOutput.id, the database scrape and reconstruction re-keyed historical outputs. Yes. In a scratch origin/main (8437a3b) checkout, main gives NUTS 2a6f5217539f82fab8ea42eda9bf3441 and SMC 3baa494f2ca7b37a8c4b85884cadd1f7. Loading that JSON or pickle under PR 2 gave b120de22… / 933c180e…, and the aggregator output id moved from f804af64… to cc9851e4…. (a) Hydration: seed.legacy_default_seed reads a NUTS/SMC 42 (from the constructor, from_dict, or __setstate__ for main pickles) as the unhashed default None. backend_seed stays 42, so sampling is bit-identical. An explicit seed=42 on NUTS/SMC therefore shares the default identity, as documented in both class docstrings, the seed.py table and docs/design/run_ctx.md Revision 3. Every other explicit NUTS/SMC seed is still hashed (the accepted re-key). (b) Aggregator: SearchOutput.id, which is also the scrape's key, now prefers the identifier the output persisted: the md5 of its .identifier description, which is what Identifier.__str__ hashes. It recomputes only when the file is absent. test_old_search_json_loads (formerly expected the re-key; it now pins main's identifier). test_nuts_smc_default_is_an_unhashed_42 (seed=42 ≡ default). test_old_nuts_smc_pickle_keeps_the_main_identifier. test_old_nuts_smc_output_keeps_the_main_identifier_in_the_aggregator, which hard-codes the two main identifiers above and checks SearchOutput.id with and without .identifier. test_search_output_id_prefers_the_persisted_identifier and …_recomputes_without_a_persisted_identifier.
2 (P2) Dynesty passed both **search_kwargs and **_rstate_kwargs(), so a subclass that already sets rstate raised TypeError: multiple values for keyword argument 'rstate'. Yes, at the real search_internal_from sampler construction for static and dynamic, pooled and unpooled. AbstractDynesty._sampler_kwargs() resolves rstate once for all four call sites. Precedence: an explicit rstate in search_kwargs wins, then the search-level seed's backend stream 1, then dynesty's own default. test_dynesty_sampler_kwargs_resolve_rstate_once, test_dynesty_subclass_with_rstate_constructs_its_sampler[static/dynamic × pooled/unpooled]. End to end, autofit_workspace_test/scripts/graphical/analytic_gaussian.py (which uses analytic_autofit.SeededDynestyStatic) passes PARITY: PASS (41/41) on this head, both unchanged and with the companion edit below applied in a scratch copy.
3 (P2) Grid-child spawn keys never reached the raw-seed backends (Nautilus, NSS, NUTS, SMC) or MultiStart's _seed_for and resurrection streams, so children shared backend randomness. Yes. Children of seed=9 had backend_seed == 9 in both, and MultiStart's broad-start draws were identical. seed.child_seed: with a spawn key, the backend gets a non-negative 31-bit seed from SeedSequence(seed, spawn_key=key). With no key (a standalone search), the raw seed passes through unchanged. Nautilus and NSS gain backend_seed, which all their backend call sites use. NUTS/SMC backend_seed derives from the seed, or from 42 by default. MultiStart._seed_for adds the spawn key. The spawn key stays unhashed and out of search.json, so no identifier changes. test_grid_children_get_distinct_raw_backend_seeds[Nautilus, NSS, BlackJAXNUTS, SMC], which checks distinct child seeds, standalone backend_seed == 9, unchanged identifiers and no serialized key. test_multi_start_grid_children_get_distinct_streams[×4], where the standalone streams equal the historical SeedSequence([9, stream]) and unseeded runs still give 0 / 1. test_raw_seed_backend_uses_backend_seed.

Superseded statements above:

  • Under "Accepted re-keys", the old JSON of default NUTS/SMC no longer re-keys (finding 1). An explicit NUTS/SMC seed=42 no longer re-keys either; it is the default.
  • Under "Decisions taken", grid children no longer share the raw backend seed (finding 3).
  • Decision for the human: a child-specific seed is derived whenever a grid child has a spawn key and the backend seed is not None. That includes default NUTS/SMC/NSS (42) and unseeded MultiStart (streams 0/1). Grid cells of those default searches therefore no longer replay identical backend randomness, as they did on main. Their identifiers and folders are unchanged. Standalone runs are bit-identical.

Gates on this head (175d91a58):

  • Full suite, serial: 3724 passed, 1 skipped, 4 xfailed (+21 tests).
  • unittest-nojax emulation: 3411 passed, 178 skipped, 2 xfailed.
  • _generate_searches.py --check: up to date.
  • Sphinx: 30 warnings.
  • 15-search identifier, hash_list and to_dict dump: identical to the previous PR 2 head. Against main it differs only by the declared seed additions and the NUTS/SMC seed: 42 → null.

Follow-up (114adeebd, test-only): CI determinism regression on unittest (3.13). test_autofit/interpolator/test_covariance.py::test_single_variable failed on 175d91a58 (27.51 == 25.0 ± 2). The cause is not a flake. The module's autouse fixture seed_search_randomness made the one-call-capped Dynesty search deterministic by seeding stdlib random, which the old Initializer drew from. This PR moved the Initializer to initializer_rng(search), which is stream 0 of SeedSequence(search.seed) and therefore OS entropy for these unseeded searches. The test went back to its measured ~3.6 % miss rate. The fix is in the fixture only: it patches seed.seed_sequence to substitute the module SEED when the search has no seed. Dynesty's existing patch stays live, because an unseeded _sampler_kwargs() passes no rstate, so dynesty still falls back to dynesty.dynesty.get_random_generator. The fixture docstring now describes the new generators. Library behaviour is unchanged. The recovered value is bit-identical across processes (24.997808837505918 ×3). test_covariance.py passed 20/20 in a loop on both 114adeebd and the rebased PR 3 head 4b86167b4, and test_autofit/interpolator + test_seed.py passed (157). The full serial suite on 4b86167b4 gave 3776 passed, 1 skipped.

🤖 Generated with Claude Code

Jammy2211 and others added 4 commits October 14, 2026 12:03
…al identifier walk

NonLinearSearch accepts seed; stream 0 seeds the initializer (start_points),
FitContext spawns it so ctx.rng.spawn(k) gives the backend streams 1..k, and
grid-search children get an independent child sequence via an unhashed spawn key.
The identifier walk appends the seed when not None for a search whose
__identifier_fields__ do not already name it.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
…global random module

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
…t 42) and seeded emcee/dynesty backends

- Nautilus, NSS, MultiStart: their seed argument is the base seed (passed to super).
- BlackJAXNUTS, SMC: seed defaults to None (backend_seed 42, unhashed); a
  user-supplied seed is hashed.
- Emcee's RandomState and dynesty's rstate come from backend stream 1 when seeded.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
…SON, old output) and witnesses

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Jammy2211 and others added 3 commits October 14, 2026 13:41
… wins

DynestyStatic/DynestyDynamic passed both **self.search_kwargs and
**self._rstate_kwargs(), so a subclass that already puts `rstate` in
`search_kwargs` (autofit_workspace_test analytic_autofit.SeededDynestyStatic)
raised `TypeError: multiple values for keyword argument 'rstate'` at sampler
construction. `_sampler_kwargs()` now resolves it once for the static and
dynamic, pooled and unpooled call sites: an explicit `rstate` in
`search_kwargs` wins, else the search-level seed's backend stream 1, else
dynesty's own default.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
…dentifier

main ran BlackJAXNUTS/SMC with an unhashed default seed=42 and recorded
`seed: 42` in every default search.json and pickle. PR 2 hydrated that 42 as a
user seed and hashed it, so SearchOutput.id, the database scrape and output
reconstruction recomputed a new identifier (NUTS 2a6f5217... -> b120de22...,
SMC 3baa494f... -> 933c180e...).

- seed.legacy_default_seed: a NUTS/SMC seed of 42 (constructor, from_dict or
  an unpickled main search via __setstate__) is the unhashed default None;
  backend_seed is still 42, so sampling is bit-identical. An explicit seed=42
  therefore shares the default identity (class docstrings, seed.py table,
  docs/design/run_ctx.md Revision 3).
- SearchOutput.id prefers the identifier the output persisted (md5 of its
  `.identifier` description) over a recompute, so a future hashing change
  cannot re-key historical outputs; outputs without the file recompute.
- test_seed.py: the old-JSON expectation now pins main's identifier; new
  pickle, aggregator (hard-coded main identifiers) and persisted-id tests.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
…nd seeds

Grid-search children carried spawn keys (0,), (1,) that only reached the
SeedSequence helpers, so the raw-seed backends (Nautilus Sampler(seed=), the
JAX PRNGKey of NSS, BlackJAXNUTS and SMC) and MultiStart's _seed_for broad-start
and resurrection streams gave every child the same randomness.

- seed.child_seed: with a spawn key, a non-negative 31-bit seed from
  SeedSequence(seed, spawn_key=key); without one (a standalone search) or with
  no seed, the raw seed unchanged, so existing seeded runs are bit-identical.
- Nautilus and NSS gain backend_seed (used at every backend call site);
  NUTS/SMC backend_seed derives from the default 42 or the seed.
- MultiStart._seed_for adds the spawn key; standalone paths unchanged.
- The spawn key stays unhashed and out of search.json.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Base automatically changed from feature/search-ext-a4-decompose to main October 14, 2026 12:58
…erpolator tests

The Initializer now draws from initializer_rng(search) (stream 0 of
SeedSequence(search.seed)), which is OS entropy for these unseeded
searches, so the autouse fixture's stdlib-random seeding no longer
controlled the start points and test_single_variable was a coin flip
again (failed on unittest 3.13). Patch seed.seed_sequence to substitute
SEED for a missing search seed; dynesty's unseeded fallback
get_random_generator patch remains live. Test-only change.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
@Jammy2211

Copy link
Copy Markdown
Collaborator Author

Companion PR: PyAutoLabs/autofit_workspace_test#111

@Jammy2211 Jammy2211 removed the pending-release PR queued for the next release build label Oct 16, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant