Skip to content
Draft
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
37 changes: 37 additions & 0 deletions .github/workflows/run_tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,43 @@ jobs:
with:
token: ${{ secrets.CODECOV_TOKEN }}

test_recipe_hssm:
name: Recipe with HSSM (CPU)
runs-on: ubuntu-latest
timeout-minutes: 15
env:
OMP_NUM_THREADS: "1"
OPENBLAS_NUM_THREADS: "1"
MLFLOW_DISABLE_AGENT_HINT: "1"
steps:
- uses: actions/checkout@v7
with:
persist-credentials: false
- uses: actions/setup-python@v6
with:
python-version: "3.12"
- uses: astral-sh/setup-uv@v7
with:
version: "latest"
enable-cache: true
cache-dependency-glob: "pyproject.toml"
- name: Install recipe and pinned HSSM consumer
run: |
uv sync --all-groups
# main identifies as 0.5.1 but is not released yet. Pin the consumer
# used for the development control, rather than a moving branch.
uv pip install "hssm @ git+https://github.com/lnccbrown/HSSM.git@1f94ce2ba5ed356209134f90a3cc6a6f8414a135"
- name: Exercise real HSSM load, ONNX gradients and fail-closed gates
run: >-
uv run --no-sync pytest tests/test_ssms_recipe.py tests/test_recipe_gradient.py
-q -o addopts= --cov=lanfactory --cov-branch
--cov-report=xml:coverage-recipe.xml --cov-report=term-missing
- name: Upload HSSM integration coverage
uses: codecov/codecov-action@v7
with:
token: ${{ secrets.CODECOV_TOKEN }}
files: coverage-recipe.xml

test_notebooks:
name: Execute tutorial notebooks
runs-on: ubuntu-latest
Expand Down
20 changes: 19 additions & 1 deletion docs/api/cli.md
Original file line number Diff line number Diff line change
@@ -1,12 +1,30 @@
# Command-line reference

LANfactory installs seven commands. The tables below describe the complete
LANfactory installs eight commands. The tables below describe the complete
command-line surface; run `COMMAND --help` to inspect the version installed in
your environment. Training commands consume LANfactory configuration files,
export commands convert saved trainer artifacts, Hub commands move reviewed
artifacts to or from a Hugging Face repository, and `derive-aux` turns a
trained LAN into an auxiliary-network training corpus.

## `lan-from-ssms`

Train, export and check a LAN from an ssms RT/choice model. All mandatory gates
must run and pass before an HSSM config is emitted. A nonpassing run exits 1 and
retains diagnostics. See [the recipe guide](../training_a_lan_for_a_new_model.md).

| Option | Required/default | Contract |
| --- | --- | --- |
| `--model TEXT` | required | Built-in or registered ssms model name |
| `--out PATH` | required | Fresh output directory |
| `--preset TEXT` | `toy` | `toy`, `dev`, or explicitly authorized `production` |
| `--model-config TEXT` | unset | Trusted `module:attribute` containing a dict or config factory |
| `--fixed-parameters TEXT` | `{}` | JSON mapping of fixed values for a conditional design |
| `--seed INTEGER` | `0` | Parameter/simulator/trainer seed |
| `--estimator TEXT` | `kde` | `kde` or PyDDM for supported single-particle two-choice diffusions |
| `--validate` / `--no-validate` | on | Disabling checks also disables HSSM config certification |
| `--allow-production` | off | Required explicit production opt-in; does not submit a job |

## `jaxtrain`

Train a JAX network. Either `--training-data-folder` or
Expand Down
10 changes: 10 additions & 0 deletions docs/api/recipes.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
# Recipes

`train_lan_for_model` joins ssms simulation, LANfactory training/export and
development validation. `LANArtifact` exposes the ONNX path, validation evidence,
manifest and (only after all mandatory checks pass) `hssm_model_config`.

See [Train a LAN for an ssms model](../training_a_lan_for_a_new_model.md) for
presets, guards, exact gate thresholds, conditional fixed parameters and limits.

::: lanfactory.recipes
100 changes: 100 additions & 0 deletions docs/training_a_lan_for_a_new_model.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
# Train a LAN for an ssms model

`train_lan_for_model` joins ssms data generation, the PyTorch trainer, concrete
single-trial ONNX export and five validation gates. It accepts built-in and
runtime-registered RT/choice models. It does not publish a network or submit jobs.

```python
from lanfactory.recipes import train_lan_for_model

artifact = train_lan_for_model("angle", "lan/angle-toy", preset="toy", seed=0)
print(artifact.validation) # toy statistical gates can fail
if artifact.validated:
import hssm
model = hssm.HSSM(
data, model="angle", loglik=str(artifact.onnx_path),
loglik_kind="approx_differentiable",
model_config=artifact.hssm_model_config,
)
```

The CLI twin is `lan-from-ssms --model angle --out lan/angle-toy --preset toy`.
It exits nonzero unless all mandatory gates ran and passed. `--no-validate`
produces diagnostic artifacts only. An existing nonempty output directory is
refused so that a failed run cannot leave a stale certificate.

## Presets

| Preset | Sets/file | Simulations/set | Labels/set | Files | Epochs | Fresh samples/check |
| --- | ---: | ---: | ---: | ---: | ---: | ---: |
| toy | 32 | 2,000 | 128 | 2 | 6 | 8,000 |
| dev | 256 | 10,000 | 512 | 4 | 40 | 20,000 |
| production | 5,000 | 200,000 | 2,000 | 300 | 100 | 200,000 |

Toy is a plumbing check. Dev supports a bounded development experiment. Neither
is a production likelihood certificate. Production data settings match the order
of magnitude of LAN_pipeline_minimal's production configs; epoch count is a
recipe default, not a measured convergence guarantee. Production additionally
requires `allow_production=True` / `--allow-production`. Run it only on an
explicitly authorized cluster. This recipe uses one generation CPU; the existing
cluster pipeline remains the scalable training/recovery/publishing route.

## Custom models and conditional designs

Pass `model_config=<ssms dict>` for a custom simulator. Numeric training bounds
are copied and normalized in `params` order; the registry is unchanged. Dependent
symbolic bounds are rejected. `generator_config` accepts nested ssms overrides;
`network_config` and `train_config` override the usual LANfactory dictionaries.
The file-level train/validation split uses distinct parameter draws. Each part's
hash, row count and theta-index offset are saved in the artifact metadata. The
batch size is adjusted to the largest divisor of file row counts no greater than
the request, with a warning and the actual value in the manifest.

Use `fixed_parameters={"a": 1.0, "z": 0.5, "t": 0.2}` for a conditional
experiment. Fixed coordinates remain in the network's input order and become
numeric fixed priors in the HSSM config. They are not free parameters. Preserve
these fixed values when fitting; the network was not trained away from them.

The CLI accepts `--model-config trusted.module:attribute` and JSON
`--fixed-parameters '{"a": 1.0}'`. Import only your own trusted model code.

## Guards and gates

ssms 0.16.0's KDE filters read the wrong config key and use non-strict boundary
comparisons ([#392](https://github.com/lnccbrown/ssm-simulators/issues/392),
[#432](https://github.com/lnccbrown/ssm-simulators/pull/432)). The recipe injects a
local guarded pipeline; it does not monkeypatch ssms. It reads
`pipeline.simulation_filters` and applies strict mode/std/choice-count thresholds.
RTs that are nonfinite/nonpositive, omissions, unknown choices and sampled
horizon hits are rejected before KDE construction. A long sequence of rejections
aborts with an actionable error. This is a conservative guard, not a resolution
of ssms' differing max_t policies ([#404](https://github.com/lnccbrown/ssm-simulators/issues/404)).
Displacement by `t` is disabled explicitly: not every model's support starts at
`t`. PyDDM labeling is optional and limited to single-particle two-choice
diffusions; it does not provide an exact oracle for arbitrary models.

| Gate | Requirement |
| --- | --- |
| G1 | Concrete single-trial ONNX, correct width, one input and one scalar output; ONNX Runtime loads/runs it. |
| G2 | Up to 1,000 training-file rows agree between the trainer and ONNX within 1e-4 absolute error. |
| G3 | HSSM accepts the explicit model config and produces finite initial logp on fresh simulated data. Missing HSSM is a skipped, nonpassing gate. |
| G4 | At five inset parameter draws, choice-weighted fresh KDE comparison: total mass in [0.9, 1.1], Hellinger <= 0.15 and distance/sampling-floor <= 3. Two independent simulations measure the floor. |
| G5 | HSSM's JAX ONNX derivative agrees with finite differences of the same graph (scaled max error <= 0.01) and with paired-seed finite differences of fresh simulated log-RT KDEs. |

G5 scales derivatives by each free parameter's training span. It uses +/- 4% of
that span and two independent paired-seed references at two RT quantiles per
choice, at five parameter draws. Reference RMS noise must be <= 0.5; the network's
RMS error must be <= 0.5 + 0.35 * reference RMS. These explicit development
thresholds are not proof of posterior calibration, and a noisy reference cannot
silently pass. Production validation needs more points, more simulation, boundary
and tail checks, and ensemble recovery in LAN_pipeline_minimal.

## Outputs

All runs write ONNX, trainer files, data parts, `manifest.json` and
`validation.json`. The manifest records configs, seeds, dependency versions,
source revision/dirty state, model-config hash, ONNX/data hashes, runtime and
rejection counts. Only a fully passing run writes `model_config.json` and sets
`artifact.hssm_model_config`. A failed/disabled/skipped gate leaves it `None`.
The HSSM bounds are exactly the training box, with fixed priors recorded explicitly.
No artifact from this recipe is marked `production_validated`.
2 changes: 2 additions & 0 deletions mkdocs.yml
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ nav:
- Learn:
- Train your first LAN (PyTorch): basic_tutorial/basic_tutorial_lan_torch.ipynb
- How-to guides:
- Train a LAN for an ssms model: training_a_lan_for_a_new_model.md
- Train with the JAX backend: basic_tutorial/basic_tutorial_lan_jax.ipynb
- Export an sbi model to ONNX: tutorials/exporting_sbi_to_onnx.ipynb
- Export a bayesflow model to ONNX: tutorials/exporting_bayesflow_to_onnx.ipynb
Expand All @@ -34,6 +35,7 @@ nav:
- onnx: api/onnx.md
- derive: api/derive.md
- network_inspectors: api/network_inspectors.md
- recipes: api/recipes.md
- trainers: api/trainers.md
- utils: api/utils.md

Expand Down
1 change: 1 addition & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -204,6 +204,7 @@ transform-jax-onnx = "lanfactory.onnx.jax_export:app"
upload-hf = "lanfactory.cli.upload_hf:app"
download-hf = "lanfactory.cli.download_hf:app"
derive-aux = "lanfactory.cli.derive_aux:app"
lan-from-ssms = "lanfactory.cli.lan_from_ssms:app"

[tool.setuptools.package-data]
"lanfactory.cli" = ["config_network_training_lan.yaml"]
62 changes: 62 additions & 0 deletions src/lanfactory/cli/lan_from_ssms.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
"""Train a bounded LAN recipe; never publish or submit a cluster job."""

import importlib
import json
from pathlib import Path

import typer

from lanfactory.recipes import train_lan_for_model

app = typer.Typer(add_completion=False)


@app.command()
def main(
model: str = typer.Option(...),
out: Path = typer.Option(...),
preset: str = typer.Option(
"toy", help="toy, dev or explicitly authorized production"
),
model_config: str | None = typer.Option(
None, help="Trusted module:attribute returning an ssms config"
),
fixed_parameters: str = typer.Option(
"{}", help="JSON mapping of fixed parameter values"
),
seed: int = typer.Option(0),
estimator: str = typer.Option("kde"),
validate: bool = typer.Option(True, "--validate/--no-validate"),
allow_production: bool = typer.Option(False),
):
config = None
if model_config:
module, name = model_config.split(":", 1)
config = getattr(importlib.import_module(module), name)
config = config() if callable(config) else config
artifact = train_lan_for_model(
model,
out,
model_config=config,
preset=preset,
estimator=estimator,
fixed_parameters=json.loads(fixed_parameters),
seed=seed,
validate=validate,
allow_production=allow_production,
)
typer.echo(
json.dumps(
{
"out": str(artifact.out_dir),
"validated": artifact.validated,
"gates": {k: v["passed"] for k, v in artifact.validation.items()},
}
)
)
if not artifact.validated:
raise typer.Exit(1)


if __name__ == "__main__":
app()
2 changes: 1 addition & 1 deletion src/lanfactory/derive/integrate.py
Original file line number Diff line number Diff line change
Expand Up @@ -378,7 +378,7 @@ def choice_mass(
theta: ArrayLike,
choices: Sequence[float] | NDArray,
onset: ArrayLike,
grid: OnsetGrid = OnsetGrid(), # noqa: B008 - frozen, so never mutated
grid: OnsetGrid = OnsetGrid(), # Frozen, so never mutated.
) -> ChoiceMass:
"""Integrate a LAN's density over reaction time for every choice.

Expand Down
5 changes: 5 additions & 0 deletions src/lanfactory/recipes/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
"""Reproducible recipes joining ssms simulation, training and validation."""

from .from_ssms import LANArtifact, train_lan_for_model

__all__ = ["LANArtifact", "train_lan_for_model"]
Loading