Repository navigation
feat: out-of-core GLM fitting, bitwise identical to the in-memory fit - #38
Merged
Merged
Conversation
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
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.
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_bytesbefore it allocates: learning, knots, the target-encoding sort and merge, moments, CV in lockstep, solve, θ and final. Learned state is capped by whatmax_bytesleaves. Work is done per slice, never per source batch. Per-row state that cannot be avoided (target-encoding training values, the Negative Binomial μ) spills toscratch_dir, and every spill file is removed however the fit ends.Full coverage.
robust=[...]).Only
store_design_matrix=Trueand per-row result accessors are refused (OutOfCoreResultError).New on every result:
fit_mode,passes,solver_settingsandsolver_trace(SolverStep). Out-of-core results also carrymemory_planandencode_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, soon_batchworks 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:
mix64(mix64(seed + m) ^ row). Same construction, different values from 0.9 for the same seed.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.RUSTYSTATS_RIDGE_CV_PCG) is removed.Other changes:
alpha_max, which now uses the weights as given.cvbelow 2 raises the sameValidationErrorin both modes, before any fit runs.polars>=2.0,<3; the lock is on Polars 2.x.HashSetordering in the monotone refine (D11);Tests and tolerances
The v0.9.0 golden record (
tests/golden/, 35 cases captured at28e7373) is new. It compares with per-field relative tolerances, because results move at rounding level:halving_exhaustedcompared 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:
encode_rowsand threads (T3);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/pythonon Polars 2.1.0: 2,529 passed, 2 skipped. On Polars 2.0.0: all pass apart fromtest_comparison.py, which that environment could not collect because it lacksstatsmodels.cargo test --workspace --release: 863 passed;cargo fmtandcargo clippy -D warningsare 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.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:
poware compared with stored v0.9.0 arrays within 4 ulps.--checkcompares 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.negbinomial_theta_estimatenow compares its θ-dependent statistics at 1e-7, where θ itself is already compared at 1e-4. On Windows,pearson_chi2comes 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.as_chunks/as_chunks_mutat the two sites it flags.ValidationErroras 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