Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 25 additions & 5 deletions .github/workflows/release.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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
Expand All @@ -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

Expand Down Expand Up @@ -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"
Expand All @@ -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:
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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:
Expand All @@ -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
Expand All @@ -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:
Expand All @@ -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/*

Expand Down
50 changes: 50 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -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.
39 changes: 35 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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.

---

Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -720,7 +751,7 @@ errors.

### Python
- `numpy` - Array operations (required)
- `polars` - DataFrame support (required)
- `polars` 2.x - DataFrame support (required)

---

Expand Down
11 changes: 6 additions & 5 deletions docs/api/dict-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

---

Expand Down
3 changes: 3 additions & 0 deletions docs/api/out-of-core.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
1 change: 1 addition & 0 deletions docs/api/serialization.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
4 changes: 2 additions & 2 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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",
]

Expand Down
16 changes: 16 additions & 0 deletions python/rustystats/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -267,6 +275,14 @@
"EncodingError",
"ValidationError",
"SerializationError",
"UnseenLabelError",
"BatchSourceChangedError",
"DesignTooWideError",
"LearnedStateTooLargeError",
"MemoryPlanExceededError",
"OutOfCoreOptionError",
"OutOfCoreResultError",
"SpillError",
# Input validation
"validate_glm_inputs",
"validate_residual_inputs",
Expand Down
22 changes: 21 additions & 1 deletion python/rustystats/formula.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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,
Expand All @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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", [])]
Expand Down
8 changes: 4 additions & 4 deletions specs/high_assurance_mutation_targets.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand All @@ -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",
Expand Down
Loading
Loading