Skip to content

feat: out-of-core GLM fitting, bitwise identical to the in-memory fit - #38

Merged
PricingFrontier merged 4 commits into
mainfrom
out-of-core-fit
Nov 5, 2026
Merged

PricingFrontier merged 4 commits into
mainfrom
out-of-core-fit

Conversation

@PricingFrontier

@PricingFrontier PricingFrontier commented Nov 5, 2026 •

Copy link
Copy Markdown
Owner

Summary

This implements specs/out-of-core-fit.md (revision 7, all of §13). rs.glm_dict(data=rs.BatchSource(open, schema), ...).fit(out_of_core=rs.OutOfCoreOptions(...)) fits any model the in-memory fit accepts. It reads the rows in passes from a re-openable source and never holds the rows, the design or any per-row array whole.

  • Bitwise identical to the in-memory fit. Both modes run one encoder, one set of drivers and fixed block-ordered reductions (4,096-row blocks). So coefficients, statistics, standard errors, smoothing, the cross-validated penalty, θ, predictions and the solver trace agree to the bit, for every batch size, encode_rows, thread count and target-encoding sort-run count.

  • Bounded memory. Each phase's planned peak (§11) is admitted against max_bytes before it allocates: learning, knots, the target-encoding sort and merge, moments, CV in lockstep, solve, θ and final. Learned state is capped by what max_bytes leaves. Work is done per slice, never per source batch. Per-row state that cannot be avoided (target-encoding training values, the Negative Binomial μ) spills to scratch_dir, and every spill file is removed however the fit ends.

  • Full coverage.

    • Every family and link, term and interaction.
    • Target and frequency encoding.
    • Fixed, penalised and monotone splines.
    • Ridge, lasso and elastic net, fixed or chosen by CV (CV with target encoding too).
    • Sign constraints, Negative Binomial θ estimation and complements.
    • Fit-time robust covariances (robust=[...]).
    • Exposure, offset, weights and complement as columns or arrays.

    Only store_design_matrix=True and per-row result accessors are refused (OutOfCoreResultError).

  • New on every result: fit_mode, passes, solver_settings and solver_trace (SolverStep). Out-of-core results also carry memory_plan and encode_rows.

  • Safety. Every pass fingerprints the columns and array inputs it reads (XXH3-128 over canonical value bytes). A source that changes between passes raises BatchSourceChangedError. Callback exceptions reach the caller unchanged, so on_batch works as a cancellation and memory-check hook.

Docs: docs/api/out-of-core.md; notes on the target-encoding order and the fold hash in the theory and regularisation pages.

Behaviour changes against v0.9.0

These are the owner decisions in spec §17, applied as recommended:

  • DEC-1: target-encoding training values use a keyed order, mix64(mix64(seed + m) ^ row). Same construction, different values from 0.9 for the same seed.
  • DEC-2: cross-validation folds use mix64(cv_seed ^ mix64(row)) mod K. Fold membership, and so the selected penalty, changes from 0.9. Folds with target encoding are now about equal in size.
  • DEC-5: List, Array, Struct, Object and Null columns are refused as categorical, frequency-encoded or target-encoded inputs, in both modes.
  • DEC-6: the undocumented PCG ridge solver (RUSTYSTATS_RIDGE_CV_PCG) is removed.

Other changes:

  • Results move at rounding level from the fixed reduction order. That includes the null fit behind alpha_max, which now uses the weights as given.
  • cv below 2 raises the same ValidationError in both modes, before any fit runs.
  • Requires polars>=2.0,<3; the lock is on Polars 2.x.
  • Fixed while specifying:
    • smooth covariance no longer falls back to the identity (D1);
    • thread-dependent reductions (D5) and the unstable fold hash (D8);
    • HashSet ordering in the monotone refine (D11);
    • θ and the Tweedie power rounded to four decimals in results (D12);
    • boundary-knot signed zeros (D13);
    • CV fold designs ignored given knots (D16).

Tests and tolerances

The v0.9.0 golden record (tests/golden/, 35 cases captured at 28e7373) is new. It compares with per-field relative tolerances, because results move at rounding level:

  • params 1e-7, statistics 1e-9, smoothing 1e-6;
  • wider overrides on the GCV and monotone smooth cases (smoothing 1e-3), separation and an ill-conditioned design (params 1e-4), and target-encoding CV;
  • halving_exhausted compared by structure only.

v0.9.0's own results on these cases move by up to 47% between thread counts (§2, §14). The six cases DEC-1 and DEC-2 change on purpose were re-captured from this build, with provenance in the record. No existing test's tolerance was loosened; rewritten tests assert exact equality where the old ones used allclose.

New coverage:

  • design digests pinned from a real v0.9.0 build (T1);
  • an in-memory against out-of-core matrix over batch sizes, encode_rows and threads (T3);
  • an abort at every pass kind, and admission at every phase (T10/T11);
  • the refusal contract (T12);
  • fingerprint keys and binding-stub parity;
  • benchmarks/bench_out_of_core_memory.py (T13/T14/T18), with a smoke run as a new CI job, out-of-core-memory-smoke.

Verification

  • pytest tests/python on Polars 2.1.0: 2,529 passed, 2 skipped. On Polars 2.0.0: all pass apart from test_comparison.py, which that environment could not collect because it lacks statsmodels.
  • cargo test --workspace --release: 863 passed; cargo fmt and cargo clippy -D warnings are clean; ruff is clean.
  • bench_out_of_core_memory.py --smoke: every check passes. Peak growth from n to 4n is at most 6.3 MiB against a 16 MiB limit, every run is within its plan, and the in-memory build is within 1.1 × 8np.
  • Haute's GLM suites (3,311 tests) pass against this build. Haute's MOD-M01 chunked GLM fitting uses it and needs this released.
  • Code review: four rounds of Codex review (gpt-6-astra, xhigh), with every finding fixed. The final round is APPROVED.

Follow-ups after opening (commits 2–4)

CI runs on CPUs whose maths library and SIMD paths differ from the development machine (AVX-512 on x86, NEON on macOS, MSVC on Windows), so a few bit-exact checks needed fixing:

  • Design digests (T1): the inputs are rounded onto a 2⁻²⁰ grid, which makes them bit-identical on every platform, and the input frame's digest is pinned on its own. The digests were re-captured from the real v0.9.0 build. Two designs whose expressions use pow are compared with stored v0.9.0 arrays within 4 ulps.
  • Oracle fixtures: --check compares the regenerated fixtures numerically, at 1e-10 relative, with exact comparison for everything else. Convergence residuals (kkt_max_abs, about 1e-11) are compared with an absolute 1e-9 tolerance.
  • New golden tolerance: negbinomial_theta_estimate now compares its θ-dependent statistics at 1e-7, where θ itself is already compared at 1e-4. On Windows, pearson_chi2 comes out 4.2e-9 relative from the record, because θ comes from a Brent search on inputs with platform-level noise. This is new in this PR; no existing tolerance was loosened.
  • Rust 1.99 clippy: as_chunks / as_chunks_mut at the two sites it flags.
  • Coverage: behavioural tests for the out-of-core and frozen-design refusal, spill-failure and edge branches. Code the parser and call chain make unreachable was removed rather than tested.
  • Smaller fixes: cross-validation now accepts link names in any case through one shared resolver, as plain fits already did. An empty source raises the same ValidationError as in memory.

CI: all 18 checks pass. The full suite has 2,700 passed and 2 skipped, and Python coverage is 97.49%.

Release

After merge, the release workflow sets the version (0.10.0). This PR does not bump it.

🤖 Generated with Claude Code

https://claude.ai/code/session_01FsfCCsY7zXRyK6EXB3ePzc

PricingFrontier and others added 4 commits November 5, 2026 22:14
Implement specs/out-of-core-fit.md. glm_dict(data=BatchSource(...)) fits any
model the in-memory fit accepts in passes over a re-openable source, under a
memory budget (OutOfCoreOptions.max_bytes) that every phase is admitted against
before it allocates. Both modes share one encoder, one set of drivers and fixed
block-ordered reductions, so they give the same bits for every batch size,
encode_rows, thread count and target-encoding sort-run count.

- Frozen design learned in bounded passes: category keys, knots, frequency and
  target encoding (keyed order, external sort spill), standardisation.
- Pass-based drivers for IRLS, coordinate descent, penalised and monotone
  smooth terms, regularisation paths, lockstep cross-validation (and CV with
  target encoding), Negative Binomial theta estimation (mu spill), complements.
- Fit-time robust covariances (robust=[...]), per-pass fingerprints,
  structural sparse/dense row kernels, and fit_mode, passes, solver_settings
  and solver_trace on every result.
- Owner decisions applied as recommended (spec section 17): DEC-1 keyed TE
  order, DEC-2 fold hash, DEC-5 nested key dtypes refused, DEC-6 PCG ridge
  solver removed. Requires polars>=2.0,<3.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FsfCCsY7zXRyK6EXB3ePzc
CI runners differ in libm/SIMD (AVX-512, NEON, MSVC), so inputs built with
np.exp/np.sin differ in the last bit across machines:

- T1 rounds every float input onto a 2^-20 grid before building the design,
  pins the input frame's digest separately, and re-captures the X/y/names
  digests from the real v0.9.0 build. The two designs whose expressions use
  pow are compared with stored v0.9.0 arrays within 4 ulps (spec §14).
- The four oracle-fixture generators compare regenerated fixtures
  numerically (1e-10 relative, everything else exact) instead of as text.
- Use as_chunks / as_chunks_mut where Rust 1.99's clippy asks for them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FsfCCsY7zXRyK6EXB3ePzc
… statistics

- Oracle --check compares KKT residuals (rounding-level, ~1e-11) with an
  absolute 1e-9 tolerance: a relative tolerance on platform noise that large
  relative to the value is meaningless, and a grown residual still fails.
- negbinomial_theta_estimate: theta comes from a Brent search already compared
  at 1e-4; its theta-dependent statistics now use 1e-7 (Windows differs by
  4.2e-9 on pearson_chi2).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FsfCCsY7zXRyK6EXB3ePzc
…ive CV links

- Behavioural tests for the refusal, spill-failure and edge branches of
  out_of_core_fit.py, out_of_core.py, category_keys.py and frozen_design.py,
  and for the lines this branch added to formula.py and interactions.py
  (test_out_of_core_paths.py, test_frozen_design_edges.py, test_formula_edges.py).
- Remove code the parser and call chain make unreachable, instead of testing it.
- Cross-validation resolves link names case-insensitively through one shared
  _alpha_link, as plain fits do (link="LOG" matched "log" everywhere else).
- An empty source raises ValidationError ("response (y) is empty") as in memory.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FsfCCsY7zXRyK6EXB3ePzc
@PricingFrontier
PricingFrontier merged commit 50e2b80 into main Nov 5, 2026
18 checks passed
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