diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 4655aa9..53330c3 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -8,6 +8,9 @@ # 3. Builds wheels for Linux/Windows/macOS × Python 3.10-3.13 # 4. Creates a GitHub Release # 5. Publishes to PyPI via trusted publishing +# +# A dry run only builds the wheels and sdist, from the commit it runs on, so they keep +# that commit's version. It makes no version commit, tag, GitHub Release or PyPI upload. name: Release @@ -19,7 +22,7 @@ on: required: true type: string dry_run: - description: "Dry run (build only, no publish)" + description: "Dry run (build only: no version commit, tag, GitHub Release or PyPI upload)" required: false type: boolean default: false @@ -34,6 +37,7 @@ jobs: outputs: version: ${{ steps.bump.outputs.version }} tag: ${{ steps.bump.outputs.tag }} + ref: ${{ inputs.dry_run && github.sha || steps.bump.outputs.tag }} steps: - uses: actions/checkout@v6 @@ -64,6 +68,7 @@ jobs: grep '^version' pyproject.toml crates/rustystats-core/Cargo.toml crates/rustystats/Cargo.toml - name: Commit and tag + if: ${{ !inputs.dry_run }} run: | git config user.name "github-actions[bot]" git config user.email "github-actions[bot]@users.noreply.github.com" @@ -82,7 +87,7 @@ jobs: steps: - uses: actions/checkout@v6 with: - ref: v${{ inputs.version }} + ref: ${{ needs.version.outputs.ref }} - uses: actions/setup-python@v6 with: @@ -112,7 +117,7 @@ jobs: steps: - uses: actions/checkout@v6 with: - ref: v${{ inputs.version }} + ref: ${{ needs.version.outputs.ref }} - uses: actions/setup-python@v6 with: @@ -142,7 +147,7 @@ jobs: steps: - uses: actions/checkout@v6 with: - ref: v${{ inputs.version }} + ref: ${{ needs.version.outputs.ref }} - uses: actions/setup-python@v6 with: @@ -168,7 +173,7 @@ jobs: steps: - uses: actions/checkout@v6 with: - ref: v${{ inputs.version }} + ref: ${{ needs.version.outputs.ref }} - name: Build sdist uses: PyO3/maturin-action@v1 @@ -187,7 +192,21 @@ jobs: name: Create GitHub Release runs-on: ubuntu-latest needs: [linux, windows, macos, sdist] + if: ${{ !inputs.dry_run }} steps: + # Before the download: checkout cleans the workspace. + - uses: actions/checkout@v6 + with: + ref: v${{ inputs.version }} + + - name: Extract this version's notes from CHANGELOG.md + run: | + awk -v header="## ${{ inputs.version }}" ' + $0 == header { found = 1; next } + found && /^## / { exit } + found { print } + ' CHANGELOG.md > release-notes.md + - name: Download all wheels uses: actions/download-artifact@v7 with: @@ -200,6 +219,7 @@ jobs: with: tag_name: v${{ inputs.version }} name: v${{ inputs.version }} + body_path: release-notes.md generate_release_notes: true files: dist/* diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..bcecf63 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,50 @@ +# Changelog + +Notable changes in each RustyStats release. For releases before 0.10.0, see +[GitHub Releases](https://github.com/PricingFrontier/rustystats/releases). + +## 0.10.0 + +### Upgrading + +- **Polars 2 is required** (`polars>=2.0,<3`). Polars 1.x is no longer supported. +- **Some fitted results change, even with the same seed:** + - Target-encoded values differ, because training rows now use a keyed order. + - Cross-validation folds differ, so the selected penalty can change. Folds with + target encoding are now about equal in size. + - Other results move at rounding level, because rows are now reduced in a fixed + order. This includes the null fit behind `alpha_max`, which now uses the weights + as given. +- **Some inputs are now refused:** List, Array, Struct, Object and Null columns as + categorical, frequency-encoded or target-encoded inputs. `cv` below 2 raises + `ValidationError` before any fit runs. +- **Removed:** the undocumented PCG ridge solver and its `RUSTYSTATS_RIDGE_CV_PCG` + setting. + +### Added + +- **Out-of-core fitting.** `rs.glm_dict(data=rs.BatchSource(open, schema), ...)` with + `.fit(out_of_core=rs.OutOfCoreOptions(...))` fits any model the in-memory fit accepts + from a re-openable source of batches, within a memory budget you set. Results are + bitwise identical to the in-memory fit. See + [Out-of-Core Fitting](https://pricingfrontier.github.io/rustystats/api/out-of-core/). +- **Robust covariances at fit time:** `fit(robust=["HC1", "HC3"])`, in either mode. +- **New on every result:** `fit_mode`, `passes`, `solver_settings` and `solver_trace`. + Out-of-core results also carry `memory_plan` and `encode_rows`. All of them survive + `to_bytes` and `from_bytes`. +- **`rs.observed_category_labels`** returns each column's sorted labels, from a + DataFrame or a `BatchSource`. +- **New exceptions**, importable from `rustystats`: `BatchSourceChangedError`, + `DesignTooWideError`, `LearnedStateTooLargeError`, `MemoryPlanExceededError`, + `OutOfCoreOptionError`, `OutOfCoreResultError`, `SpillError` and `UnseenLabelError`. + +### Fixed + +- Results no longer depend on the thread count or on run-to-run scheduling, and + cross-validation folds no longer depend on the Rust release. +- A smooth covariance that cannot be inverted now raises, instead of falling back to + the identity matrix. +- Scale, log-likelihood, null deviance, standard errors and residuals now use the exact + θ and Tweedie power, not values rounded to four decimals. +- Cross-validation fold designs now honour `knots=`. +- Cross-validation accepts link names in any case, as plain fits already did. diff --git a/README.md b/README.md index cabb765..7ee660a 100644 --- a/README.md +++ b/README.md @@ -19,9 +19,10 @@ - **Target Encoding** - Ordered target encoding for high-cardinality categoricals - **Regularization** - Ridge, Lasso, and Elastic Net via coordinate descent - **Lasso Credibility** - Shrink toward a prior model instead of zero (CAS Monograph 13) +- **Out-of-Core** - Fit from batches within a memory budget, bitwise identical to the in-memory fit - **Validation** - Design matrix checks with fix suggestions before fitting - **Complete** - 8 families, robust SEs, full diagnostics, VIF, partial dependence -- **Minimal** - Only `numpy` and `polars` required +- **Minimal** - Only `numpy` and `polars` 2 required ## Installation @@ -319,13 +320,14 @@ result = rs.glm_dict( "age2": {"type": "expression", "expr": "age ** 2"}, "age3": {"type": "expression", "expr": "age ** 3"}, "income_k": {"type": "expression", "expr": "income / 1000"}, - "bmi": {"type": "expression", "expr": "weight / (height ** 2)"}, + "power_to_weight": {"type": "expression", "expr": "power / weight"}, }, data=data, family="gaussian", ).fit() ``` -**Supported operations:** `+`, `-`, `*`, `/`, `**` (power) +**Supported operations:** `+`, `-`, `*`, `/`, `**` (power). An expression is one operation on +columns or numbers. For anything else, such as a log, add the column to your DataFrame first. --- @@ -405,6 +407,35 @@ Works with all families/links, splines, categoricals, interactions, and target e --- +## Out-of-Core Fitting + +Fit data too large for memory from a source that can be re-read in batches. Memory is bounded +by a budget you set, and the result is bitwise identical to an in-memory fit. + +```python +import polars as pl +import rustystats as rs + +path = "training.parquet" + +def open_batches(columns): + # Every call must yield the same rows in the same order. + yield from pl.scan_parquet(path).select(columns).collect_batches() + +result = rs.glm_dict( + response="ClaimCount", + terms={"Age": {"type": "bs", "df": 5}, "Region": {"type": "categorical"}}, + data=rs.BatchSource(open_batches, pl.read_parquet_schema(path)), + family="poisson", + exposure="Exposure", +).fit(out_of_core=rs.OutOfCoreOptions(max_bytes=2 * 1024**3)) +``` + +See [Out-of-Core Fitting](https://pricingfrontier.github.io/rustystats/api/out-of-core/) for +the options and what a result serves. + +--- + ## Design Matrix Validation ```python @@ -720,7 +751,7 @@ errors. ### Python - `numpy` - Array operations (required) -- `polars` - DataFrame support (required) +- `polars` 2.x - DataFrame support (required) --- diff --git a/docs/api/dict-api.md b/docs/api/dict-api.md index 17ad427..a78d227 100644 --- a/docs/api/dict-api.md +++ b/docs/api/dict-api.md @@ -363,22 +363,23 @@ terms = { ### expression -Arbitrary arithmetic expressions (like R's `I()`). +One arithmetic operation on columns or numbers (like a simple R `I()`). ```python terms = { "Age2": {"type": "expression", "expr": "Age ** 2"}, - "BMI": {"type": "expression", "expr": "Weight / (Height ** 2)"}, - "LogDensity": {"type": "expression", "expr": "log(Density)"}, + "IncomeK": {"type": "expression", "expr": "Income / 1000"}, + "PowerToWeight": {"type": "expression", "expr": "Power / Weight"}, } ``` | Parameter | Type | Description | |-----------|------|-------------| -| `expr` | str | Python expression using column names | +| `expr` | str | One operation on a column and a column or number | | `monotonicity` | str | `"increasing"` or `"decreasing"` (optional) | -**Supported operations:** `+`, `-`, `*`, `/`, `**`, `log`, `exp`, `sqrt` +**Supported operations:** `+`, `-`, `*`, `/`, `**`. For anything else, such as a log or a +compound formula, add the column to your DataFrame first. --- diff --git a/docs/api/out-of-core.md b/docs/api/out-of-core.md index aad305b..176d544 100644 --- a/docs/api/out-of-core.md +++ b/docs/api/out-of-core.md @@ -73,6 +73,9 @@ category, L1 with a smooth term, and so on) are refused before the source is ope | `scratch_dir` | Where spill files go. Required for target encoding and for θ estimation. Every spill file is removed when the fit ends, however it ends. | | `on_batch` | Called with a `BatchProgress(pass_index, pass_kind, rows_done, n_rows)` after every source batch. An exception it raises stops the fit and reaches the caller unchanged: use it for cancellation and memory checks. | +Every error named on this page can be caught from the package, for example +`except rs.MemoryPlanExceededError`. + ## Results Both modes report how the fit ran: diff --git a/docs/api/serialization.md b/docs/api/serialization.md index cc8acd6..04e123e 100644 --- a/docs/api/serialization.md +++ b/docs/api/serialization.md @@ -118,6 +118,7 @@ The serialized model includes everything needed for prediction: | Frequency encoding stats | ✓ | Level frequencies | | Input transforms | ✓ | Deterministic lookup specs for raw-data scoring | | Formula/term specs | ✓ | For design matrix construction | +| Fit record | ✓ | `fit_mode`, `passes`, `solver_settings`, `solver_trace`; `memory_plan` and `encode_rows` for out-of-core fits | For `MultinomialModel`, serialization also preserves class order, reference class, the coefficient matrix, alternative-term specifications and diff --git a/pyproject.toml b/pyproject.toml index 9db8f1d..9bb094a 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -42,8 +42,8 @@ keywords = ["statistics", "glm", "actuarial", "regression", "modeling"] # Python package dependencies (minimal for users) dependencies = [ "numpy>=1.20,<2.4", - # The oldest Polars the package runs on: 1.32 has no hash joins on Decimal - # (i128) category keys, which 1.33 has (checked by running the suite on both). + # Polars 2 is the supported line: the lock runs the suite on 2.0 (Python 3.10) + # and 2.1 (Python 3.11+). "polars>=2.0,<3", ] diff --git a/python/rustystats/__init__.py b/python/rustystats/__init__.py index ebaa3dd..ba158cc 100644 --- a/python/rustystats/__init__.py +++ b/python/rustystats/__init__.py @@ -109,13 +109,21 @@ # Exceptions from rustystats.exceptions import ( + BatchSourceChangedError, ConvergenceError, DesignMatrixError, + DesignTooWideError, EncodingError, FittingError, + LearnedStateTooLargeError, + MemoryPlanExceededError, + OutOfCoreOptionError, + OutOfCoreResultError, PredictionError, RustyStatsError, SerializationError, + SpillError, + UnseenLabelError, ValidationError, ) from rustystats.export_onnx import to_onnx @@ -267,6 +275,14 @@ "EncodingError", "ValidationError", "SerializationError", + "UnseenLabelError", + "BatchSourceChangedError", + "DesignTooWideError", + "LearnedStateTooLargeError", + "MemoryPlanExceededError", + "OutOfCoreOptionError", + "OutOfCoreResultError", + "SpillError", # Input validation "validate_glm_inputs", "validate_residual_inputs", diff --git a/python/rustystats/formula.py b/python/rustystats/formula.py index f411372..115ebda 100644 --- a/python/rustystats/formula.py +++ b/python/rustystats/formula.py @@ -29,7 +29,7 @@ import warnings import weakref from collections.abc import Sequence -from dataclasses import dataclass +from dataclasses import asdict, dataclass from typing import TYPE_CHECKING, Any import numpy as np @@ -3960,6 +3960,7 @@ def to_bytes(self) -> bytes: # Extract state from the Rust result object # NOTE: We intentionally exclude fittedvalues and linear_predictor # as they are large arrays not needed for prediction (can be ~5MB each) + memory_plan = self.__dict__.get("memory_plan") result_state = { "params": np.asarray(self._result.params), "deviance": self._result.deviance, @@ -3982,6 +3983,14 @@ def to_bytes(self) -> bytes: "max_std_score": self.__dict__.get("max_std_score"), "regularization_standardized": self.__dict__.get("_regularization_standardized", False), "covariance_available": self.__dict__.get("_covariance_available", True), + # How the fit ran, as plain values: reading a payload never needs the + # classes that hold them. + "fit_mode": self.__dict__.get("fit_mode"), + "passes": self.__dict__.get("passes"), + "solver_settings": self.__dict__.get("solver_settings"), + "solver_trace": [tuple(step) for step in self.__dict__.get("solver_trace", ())], + "memory_plan": asdict(memory_plan) if memory_plan is not None else None, + "encode_rows": self.__dict__.get("encode_rows"), } # Extract builder state for prediction @@ -4085,6 +4094,9 @@ def from_bytes(cls, data: bytes) -> GLMModel: """ import pickle + from rustystats.out_of_core_fit import MemoryPlan + from rustystats.solver_trace import solver_steps + state = pickle.loads(data) # Fail loud on a schema this build cannot read, rather than silently @@ -4165,6 +4177,14 @@ def from_bytes(cls, data: bytes) -> GLMModel: model.step_halving_used = result_state.get("step_halving_used") model.stationary = result_state.get("stationary") model.max_std_score = result_state.get("max_std_score") + # A payload written before these were recorded came from an in-memory fit. + model.fit_mode = result_state.get("fit_mode") or "in_memory" + model.passes = result_state.get("passes") or {} + model.solver_settings = result_state.get("solver_settings") or {} + model.solver_trace = solver_steps(result_state.get("solver_trace")) + if result_state.get("memory_plan") is not None: + model.memory_plan = MemoryPlan(**result_state["memory_plan"]) + model.encode_rows = result_state["encode_rows"] model._intercept_delta = float(state.get("intercept_delta", 0.0)) model._intercept_delta_var = float(state.get("intercept_delta_var", 0.0)) model._relevel_history = [dict(entry) for entry in state.get("relevel_history", [])] diff --git a/specs/high_assurance_mutation_targets.json b/specs/high_assurance_mutation_targets.json index 9efc92f..a9f83c7 100644 --- a/specs/high_assurance_mutation_targets.json +++ b/specs/high_assurance_mutation_targets.json @@ -40,8 +40,8 @@ "module": "crates/rustystats-core/src/families/poisson.rs", "path": "crates/rustystats-core/src/families/poisson.rs", "description": "Poisson variance must equal the mean.", - "original": "Cow::Borrowed(mu)", - "mutated": "Cow::Owned(mu.mapv(|x| x + 1.0))", + "original": "fn variance_at(&self, mu: f64) -> f64 {\n mu\n }", + "mutated": "fn variance_at(&self, mu: f64) -> f64 {\n mu + 1.0\n }", "test_command": [ "cargo", "test", @@ -58,8 +58,8 @@ "module": "crates/rustystats-core/src/links/log.rs", "path": "crates/rustystats-core/src/links/log.rs", "description": "Log-link derivative must be 1 / mu.", - "original": "mu.mapv(|x| 1.0 / x)", - "mutated": "mu.mapv(|x| x)", + "original": "fn derivative_at(&self, mu: f64) -> f64 {\n 1.0 / mu\n }", + "mutated": "fn derivative_at(&self, mu: f64) -> f64 {\n mu\n }", "test_command": [ "cargo", "test", diff --git a/specs/roadmap/bug.md b/specs/roadmap/bug.md new file mode 100644 index 0000000..a446d4f --- /dev/null +++ b/specs/roadmap/bug.md @@ -0,0 +1,407 @@ +s", "monotonicity": "decreasing"}, + "PreviousRenewal": {"type": "categorical"}, + "include_main": True, + }, +] +``` + +For the reference category (`PreviousRenewal=0`), the fitted price curve is +non-increasing. For `PreviousRenewal=1`, the model uses: + +```text +main InvitedPremiumDiff smooth + PreviousRenewal[T.1]:InvitedPremiumDiff smooth +``` + +The main smooth is constrained, but the interaction block is not registered as a +monotone smooth block. The combined curve can therefore increase. + +## Self-Contained Repro + +This should reproduce on rustystats 0.8.15 without any private data. + +Install: + +```bash +pip install "rustystats==0.8.15" "polars" "numpy" +``` + +Save as `repro_monotone_interaction.py`: + +```python +import numpy as np +import polars as pl +import rustystats as rs + +rng = np.random.default_rng(7) +n = 4000 + +x = rng.uniform(0.0, 1.0, n) +g = rng.integers(0, 2, n) + +# The baseline effect is decreasing in x. +# Group 1 has an increasing local bump. A correct monotone interaction +# implementation should not be able to learn an increasing group-specific curve. +eta = 2.0 - 4.0 * x + (g == 1) * (3.5 * np.exp(-((x - 0.75) / 0.10) ** 2)) +y = eta + rng.normal(0.0, 0.15, n) + +df = pl.DataFrame( + { + "y": y, + "x": x, + "g": g.astype(str), + } +) + +interactions = [ + { + "x": {"type": "bs", "monotonicity": "decreasing"}, + "g": {"type": "categorical"}, + "include_main": True, + }, +] + +model = rs.glm_dict( + response="y", + terms={}, + interactions=interactions, + data=df, + family="gaussian", + link="identity", + seed=42, +).fit() + +print("converged", getattr(model, "converged", None)) +print("stationary", getattr(model, "stationary", None)) + +print("\nCoefficient block containing x") +for i, name in enumerate(model.feature_names): + if "x" in name: + print(i, name, float(model.params[i])) + + +def check_group(group, lo=0.01, hi=0.99, n_grid=201): + grid = pl.DataFrame( + { + "x": np.linspace(lo, hi, n_grid), + "g": [str(group)] * n_grid, + } + ) + pred = np.asarray(model.predict(grid), dtype=float) + diff = np.diff(pred) + return { + "group": group, + "max_increase": float(diff.max()), + "upward_steps": int((diff > 1e-8).sum()), + "min_prediction": float(pred.min()), + "max_prediction": float(pred.max()), + } + + +print("\nInterior monotonicity checks, x in [0.01, 0.99]") +for group in (0, 1): + print(check_group(group)) + +print("\nExpected invariant after fix:") +print(" max_increase <= 0 and upward_steps == 0 for every group") +``` + +Observed on rustystats 0.8.15: + +```text +converged True +stationary True + +Interior monotonicity checks, x in [0.01, 0.99] +{'group': 0, 'max_increase': negative, 'upward_steps': 0, ...} +{'group': 1, 'max_increase': about 0.10, 'upward_steps': about 44, ...} +``` + +The coefficient block also shows the failure mode. The main `bs(x, ..., k, -)` +coefficients are monotone decreasing, but the interaction coefficients +`g[T.1]:bs(x, ..., k, -)` are unconstrained and non-monotone. + +## Production Evidence + +The renewal annual model has this interaction: + +```python +interactions = [ + { + "InvitedPremiumDiff": {"type": "bs", "monotonicity": "decreasing"}, + "PreviousRenewal": {"type": "categorical"}, + "include_main": True, + }, +] +``` + +The model fit was solver-clean: + +```text +converged=True +stationary=True +solver_status=converged +train mean gap ~= +0.00074 +``` + +But a function sweep of `InvitedPremiumDiff` over the training rows produced: + +```text +PreviousRenewal=0: + rows_violating = 0 / 2931 + +PreviousRenewal=1: + rows_violating = 3448 / 3448 + max increase ~= 0.00238 per grid step +``` + +So the main constrained smooth is not enough. The category-specific combined +curve is allowed to rise. + +In the renewal optimiser grid this appeared as annual-only guard clipping: + +```text +Applied renewal monotone grid guard: + 9878 raw model grid points clipped across 604 policies + immediate raw upward steps before cumulative-min guard: 6657 + max immediate increase ~= 0.03095 + max increase above cumulative guard ~= 0.23075 + split by payment type: annual only +``` + +The largest apparent impact was a trough-and-recovery shape. A low value at one +commission rate was carried forward by the cumulative-min score-time guard, then +later raw predictions recovered above it. + +## Where The Bug Is + +Relevant rustystats paths: + +```text +python/rustystats/formula.py +python/rustystats/interactions.py +crates/rustystats/src/fitting_py.rs +crates/rustystats-core/src/solvers/smooth_glm.rs +``` + +Specific flow: + +1. `formula.py::_parse_interaction_spec` + - Creates an `InteractionTerm` for the categorical spline interaction. + - If `include_main=True`, it separately adds the main effect via + `_parse_term_spec`. + +2. `interactions.py::InteractionBuilder.build_design_matrix_from_parsed` + - Builds and records smooth term ranges for `parsed.spline_terms`. + - This happens before interaction columns are appended. + +3. `interactions.py::InteractionBuilder._build_mixed_interaction` + - Builds `categorical x spline` columns. + - Names look like: + +```text +PreviousRenewal[T.1]:bs(InvitedPremiumDiff, 1/9, k, -) +... +PreviousRenewal[T.1]:bs(InvitedPremiumDiff, 9/9, k, -) +``` + + - These columns are returned as ordinary interaction columns. + - They are not registered in `_smooth_terms` / `_smooth_col_indices`. + +4. `formula.py::_fit_with_smooth_penalties` + - Passes only the registered smooth column ranges to Rust. + - The interaction block is not included in `smooth_col_ranges`. + +5. `formula.py::_get_constraint_indices` + - Explicitly avoids sign-clamping names containing `", k,"`, because smooth + terms are expected to be handled by the smooth solver. + - The interaction columns contain `", k,"`, but they were not registered with + the smooth solver either. + +6. `crates/rustystats/src/fitting_py.rs::fit_smooth_glm_unified_py` + - Only enforces monotonicity for column ranges supplied in + `smooth_col_ranges`. + +7. `crates/rustystats-core/src/solvers/smooth_glm.rs` + - The alpha-to-beta monotone reparameterization is applied only to those + supplied ranges. + +Net result: monotone spline interaction columns fall between two systems: + +```text +not sign-clamped because they look like smooth k terms +not smooth-constrained because they are not registered smooth ranges +``` + +## Additional Issues Identified + +### 1. Function-level monotonicity is not asserted + +The library currently trusts coefficient constraints / smooth metadata. The bug +would have been caught by a post-fit function check: + +```text +for every monotone term: + for every relevant categorical interaction level: + score a dense grid over the training range + assert non-increasing / non-decreasing within tolerance +``` + +This should be part of the model fit validation path, at least in debug/test +mode, and ideally available as a public diagnostic. + +### 2. Combined monotonicity matters, not just component monotonicity + +For `include_main=True`, the non-reference level uses: + +```text +f_level(x) = f_main(x) + f_interaction_level(x) +``` + +The required invariant is that `f_level(x)` is monotone for each level. There +are two possible implementations: + +- Conservative: require both `f_main` and every `f_interaction_level` to be + monotone in the same direction. The sum is then monotone. +- More flexible: enforce monotonicity on the combined coefficients/function for + each level. This requires coupled constraints between the main block and the + interaction block. + +The first option is simpler and probably acceptable as a first fix. The second +is statistically less restrictive. + +### 3. Score-time out-of-training-range values can create extreme artefacts + +In the production optimiser, some price-derived features can move far outside +the train range. Example from the annual grid: + +```text +RatioToMarket > 13 +``` + +while the train 99th percentile was around: + +```text +RatioToMarket ~= 2.5 +``` + +This can produce very large prediction jumps at score time. The renewal +application now clips `InvitedPremiumDiff` and applies a cumulative-min guard, +but rustystats should consider one or more of: + +- expose train boundary knots/ranges clearly; +- warn or error when scoring far outside fitted spline boundaries; +- optionally clamp spline inputs to boundary knots; +- provide a monotonicity diagnostic that checks both in-range and out-of-range + score grids. + +### 4. Duplicate row IDs can create false diagnostic jumps + +The saved renewal parquet has duplicate `POLICY_DETAILS_ID`s. Diagnostics that +group by policy id can accidentally compare different rows as adjacent price +steps and create artificial jumps. Repro/diagnostic code should use a stable +row id when constructing grids unless the input is known to be one row per +policy. + +This is not a rustystats solver bug, but it matters when validating examples. + +### 5. Regularization plus monotonicity needs an explicit API decision + +Earlier solver work found that some regularized paths can bypass/drop monotone +constraints. The API should not silently accept an unsupported combination. + +Recommended behaviour: + +```text +if regularization is requested and any monotonicity constraint is present: + either support the constraints correctly + or raise a hard error +``` + +Silent warnings are too easy to miss for production pricing models. + +### 6. Boundary / identifiability edge should be tested + +The B-spline basis drops a column for identifiability and relies on the +intercept plus coefficient sequencing. Synthetic checks over exact endpoints or +outside fitted boundary knots can show large jumps even when the interior grid +is monotone. + +At minimum, add tests covering: + +- dense interior grid over the fitted training range; +- exact fitted boundary knots; +- values just outside the fitted boundary knots; +- models with and without an intercept; +- dropped-column B-spline basis with monotonicity enabled. + +## Suggested Fix Plan + +### Immediate hardening + +Add detection in `formula.py::_parse_interaction_spec`: + +```text +if an interaction contains a spline term with monotonicity: + if categorical factors are present: + raise NotImplementedError / ValidationError +``` + +This prevents the current silent wrong behaviour while the full fix is built. + +### Full support + +In `InteractionBuilder._build_mixed_interaction`, when constructing +`categorical x monotone spline` columns: + +1. Preserve the spline metadata for each category-specific block: + - column start; + - column end; + - penalty matrix; + - monotonicity direction; + - source variable; + - category level. + +2. Include those ranges in `smooth_col_ranges` passed to + `fit_smooth_glm_unified_py`. + +3. Decide whether interaction blocks should be constrained independently or + whether the combined `main + interaction` level curve should be constrained. + +4. Add a post-fit function-level monotonicity check over every constrained + term and category level. + +### Regression tests + +Add a test using the synthetic repro above. The fixed invariant should be: + +```text +for group in (0, 1): + max(diff(model.predict(grid_for_group))) <= tolerance +``` + +Also add tests for: + +```text +monotone bs main effect only +monotone bs x categorical with include_main=True +monotone bs x categorical with include_main=False +monotone bs x continuous interaction, or hard error if unsupported +regularization + monotonicity hard error or correct support +score-time values outside fitted boundary knots +``` + +## Temporary Application Mitigation + +The renewal optimiser now applies a score-time cumulative minimum over each +policy's ascending commission grid: + +```text +RenewalPrediction_guarded[c] = min( + RenewalPrediction_raw[c], + RenewalPrediction_guarded[c - 1], +) +``` + +This is conservative and guarantees the optimiser cannot prefer a higher price +because the raw retention model spuriously increased. It is not a substitute for +fixing the library, because it can be too punitive after a spurious trough. \ No newline at end of file diff --git a/tests/python/test_out_of_core_contract.py b/tests/python/test_out_of_core_contract.py index 2a3723b..1f9439b 100644 --- a/tests/python/test_out_of_core_contract.py +++ b/tests/python/test_out_of_core_contract.py @@ -14,6 +14,7 @@ from __future__ import annotations +import pickle import re import tracemalloc from dataclasses import dataclass @@ -24,6 +25,7 @@ import pytest import rustystats as rs from _golden_cases import CASES, RESULT_FIELDS, _read, design_frame +from rustystats import exceptions from rustystats.exceptions import ( DesignTooWideError, LearnedStateTooLargeError, @@ -845,6 +847,73 @@ def test_an_out_of_core_result_refuses_each_per_row_method(frame) -> None: assert diagnostics is not None +# ── §4.5: the fit record through to_bytes ─────────────────────────────────── + + +RECORD_GLM = { + "response": "y_pois", + "family": "poisson", + "terms": {"x1": {"type": "linear"}, "cat_a": {"type": "categorical"}}, +} + + +def _record(result: rs.GLMModel) -> tuple: + return result.fit_mode, result.passes, result.solver_settings, result.solver_trace + + +@pytest.mark.parametrize("out_of_core", [False, True], ids=["in_memory", "out_of_core"]) +def test_a_restored_result_reports_how_the_fit_ran(frame, out_of_core: bool) -> None: + if out_of_core: + result = rs.glm_dict(data=_source(frame)[0], **RECORD_GLM).fit( + out_of_core=rs.OutOfCoreOptions() + ) + else: + result = rs.glm_dict(data=frame, **RECORD_GLM).fit() + + restored = rs.GLMModel.from_bytes(result.to_bytes()) + + assert _record(restored) == _record(result) + assert restored.solver_trace + assert all(isinstance(step, rs.SolverStep) for step in restored.solver_trace) + if out_of_core: + assert restored.memory_plan == result.memory_plan + assert restored.encode_rows == result.encode_rows + + +def test_a_restored_out_of_core_result_still_refuses_per_row_methods(frame) -> None: + result = rs.glm_dict(data=_source(frame)[0], **RECORD_GLM).fit( + out_of_core=rs.OutOfCoreOptions() + ) + restored = rs.GLMModel.from_bytes(result.to_bytes()) + + with pytest.raises(OutOfCoreResultError, match="relevel"): + restored.relevel(frame) + + +def test_a_payload_without_the_fit_record_reads_as_an_in_memory_fit(frame) -> None: + """0.9.0 wrote the same schema version without these fields.""" + state = pickle.loads(rs.glm_dict(data=frame, **RECORD_GLM).fit().to_bytes()) + for key in ( + "fit_mode", + "passes", + "solver_settings", + "solver_trace", + "memory_plan", + "encode_rows", + ): + del state["result_state"][key] + + restored = rs.GLMModel.from_bytes(pickle.dumps(state)) + + assert _record(restored) == ("in_memory", {}, {}, ()) + + +def test_every_exception_can_be_caught_from_the_package() -> None: + for name in exceptions.__all__: + assert getattr(rs, name) is getattr(exceptions, name), name + assert name in rs.__all__, name + + # ── §6.8: array inputs ──────────────────────────────────────────────────────