From d946886a685732f87744b0ac9c4f926b7ae5e907 Mon Sep 17 00:00:00 2001 From: Francesco Muia Date: Tue, 24 Nov 2026 13:17:29 +0100 Subject: [PATCH 1/5] Add bounded ssms LAN recipe with density and gradient gates --- docs/training_a_lan_for_a_new_model.md | 100 +++++++ mkdocs.yml | 1 + pyproject.toml | 1 + src/lanfactory/cli/lan_from_ssms.py | 60 ++++ src/lanfactory/recipes/__init__.py | 5 + src/lanfactory/recipes/from_ssms.py | 398 +++++++++++++++++++++++++ src/lanfactory/recipes/guards.py | 123 ++++++++ src/lanfactory/recipes/validation.py | 353 ++++++++++++++++++++++ tests/test_recipe_gradient.py | 79 +++++ tests/test_ssms_recipe.py | 238 +++++++++++++++ 10 files changed, 1358 insertions(+) create mode 100644 docs/training_a_lan_for_a_new_model.md create mode 100644 src/lanfactory/cli/lan_from_ssms.py create mode 100644 src/lanfactory/recipes/__init__.py create mode 100644 src/lanfactory/recipes/from_ssms.py create mode 100644 src/lanfactory/recipes/guards.py create mode 100644 src/lanfactory/recipes/validation.py create mode 100644 tests/test_recipe_gradient.py create mode 100644 tests/test_ssms_recipe.py diff --git a/docs/training_a_lan_for_a_new_model.md b/docs/training_a_lan_for_a_new_model.md new file mode 100644 index 0000000..9dc25cf --- /dev/null +++ b/docs/training_a_lan_for_a_new_model.md @@ -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=` 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`. diff --git a/mkdocs.yml b/mkdocs.yml index 23afd30..6ffd603 100755 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -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 diff --git a/pyproject.toml b/pyproject.toml index 5635170..23c8de6 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -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"] diff --git a/src/lanfactory/cli/lan_from_ssms.py b/src/lanfactory/cli/lan_from_ssms.py new file mode 100644 index 0000000..71a5ba4 --- /dev/null +++ b/src/lanfactory/cli/lan_from_ssms.py @@ -0,0 +1,60 @@ +"""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 = "toy", + 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 = 0, + estimator: str = "kde", + validate: bool = True, + allow_production: bool = 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() diff --git a/src/lanfactory/recipes/__init__.py b/src/lanfactory/recipes/__init__.py new file mode 100644 index 0000000..0354b74 --- /dev/null +++ b/src/lanfactory/recipes/__init__.py @@ -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"] diff --git a/src/lanfactory/recipes/from_ssms.py b/src/lanfactory/recipes/from_ssms.py new file mode 100644 index 0000000..76274a6 --- /dev/null +++ b/src/lanfactory/recipes/from_ssms.py @@ -0,0 +1,398 @@ +"""One-call, bounded ssms -> PyTorch -> ONNX -> HSSM recipe.""" + +import hashlib +import importlib.metadata +import inspect +import json +import subprocess +import time +import warnings +from copy import deepcopy +from dataclasses import asdict, dataclass +from datetime import UTC, datetime +from pathlib import Path + +import numpy as np + +from . import validation as gates +from .guards import GuardedSimulationPipeline, normalize_model_config + + +@dataclass(frozen=True) +class Preset: + n_parameter_sets: int + n_simulations: int + n_samples_per_param: int + n_files: int + n_epochs: int + validation_n: int + + +PRESETS = { + "toy": Preset(32, 2000, 128, 2, 6, 8000), + "dev": Preset(256, 10000, 512, 4, 40, 20000), + "production": Preset(5000, 200000, 2000, 300, 100, 200000), +} + + +@dataclass +class LANArtifact: + onnx_path: Path + hssm_model_config: dict | None + validation: dict + manifest: dict + out_dir: Path + + @property + def validated(self): + return all( + self.validation.get(g, {}).get("passed") is True + and not self.validation[g].get("skipped", False) + for g in ("G1", "G2", "G3", "G4", "G5") + ) + + +def _describe(value): + if isinstance(value, dict): + return {str(k): _describe(v) for k, v in value.items()} + if isinstance(value, (list, tuple)): + return [_describe(v) for v in value] + if isinstance(value, np.ndarray): + return _describe(value.tolist()) + if isinstance(value, np.generic): + return _describe(value.item()) + if isinstance(value, Path): + return str(value) + if isinstance(value, float) and not np.isfinite(value): + return None + if value is None or isinstance(value, (str, int, float, bool)): + return value + if callable(value): + try: + source = inspect.getsource(value) + except (TypeError, OSError): + source = "unavailable" + return { + "callable": f"{value.__module__}.{value.__qualname__}", + "source_sha256": hashlib.sha256(source.encode()).hexdigest(), + } + return { + "type": f"{type(value).__module__}.{type(value).__qualname__}", + "state": _describe(vars(value)), + } + + +def _write(path, data): + path.write_text(json.dumps(_describe(data), indent=2, allow_nan=False) + "\n") + + +def _sha(path): + return hashlib.sha256(Path(path).read_bytes()).hexdigest() + + +def batch_divisor(n_rows, requested): + if n_rows <= 0 or requested <= 0: + raise ValueError("row count and batch size must be positive") + actual = next(i for i in range(min(n_rows, requested), 0, -1) if n_rows % i == 0) + if actual != requested: + warnings.warn( + f"batch_size {requested} does not divide {n_rows} rows; using {actual}", + stacklevel=2, + ) + return actual + + +def _source_revision(): + try: + root = Path(__file__).resolve().parents[3] + sha = subprocess.check_output( + ["git", "rev-parse", "HEAD"], cwd=root, text=True, stderr=subprocess.DEVNULL + ).strip() + dirty = bool( + subprocess.check_output( + ["git", "status", "--porcelain"], cwd=root, text=True + ) + ) + return {"commit": sha, "dirty": dirty} + except (OSError, subprocess.CalledProcessError): + return {"commit": None, "dirty": None} + + +def train_lan_for_model( + model: str, + out_dir: str | Path, + *, + model_config: dict | None = None, + preset: str = "toy", + estimator: str = "kde", + network_config: dict | None = None, + train_config: dict | None = None, + generator_config: dict | None = None, + fixed_parameters: dict | None = None, + seed: int = 0, + validate: bool = True, + allow_production: bool = False, +) -> LANArtifact: + """Train a LAN and return evidence, including failures. + + A failed/skipped/disabled mandatory gate prevents ``model_config.json`` + from being written and leaves ``hssm_model_config`` as None. The ONNX and + manifest remain available for diagnosis. Toy/dev are never production + certificates. ``fixed_parameters`` explicitly fixes a conditional design; + those values are included as fixed HSSM priors, never fitted/extrapolated. + + ``generator_config`` overrides nested ssms settings. n_files is controlled + by the preset, n_cpus is always one locally. Production requires explicit + opt-in; the recipe does not submit or publish anything. + """ + if preset not in PRESETS: + raise ValueError(f"unknown preset {preset!r}; choose {list(PRESETS)}") + if preset == "production" and not allow_production: + raise ValueError( + "production requires allow_production=True and an explicitly authorized cluster run" + ) + if seed < 0: + raise ValueError("seed must be nonnegative") + settings = PRESETS[preset] + import cloudpickle + import torch + from ssms.config import ModelConfigBuilder, get_lan_kde_config + from ssms.dataset_generators.estimator_builders.kde_builder import ( + KDEEstimatorBuilder, + ) + from ssms.dataset_generators.lan_mlp import TrainingDataGenerator + from ssms.dataset_generators.strategies import ResampleMixtureStrategy + + from lanfactory.config.network_configs import network_config_mlp, train_config_mlp + from lanfactory.trainers.torch_mlp import ( + ModelTrainerTorchMLP, + TorchMLPFactory, + make_train_valid_dataloaders, + ) + + cfg = normalize_model_config( + ModelConfigBuilder.from_model(model) if model_config is None else model_config, + fixed_parameters, + ) + if cfg["name"] != model: + raise ValueError("model and model_config name must agree") + gen = get_lan_kde_config(model) + gen["pipeline"].update( + n_parameter_sets=settings.n_parameter_sets, + n_subruns=1, + n_cpus=1, + parameter_sampler_index_offset=seed + * settings.n_files + * settings.n_parameter_sets, + ) + gen["simulator"]["n_samples"] = settings.n_simulations + gen["training"]["n_samples_per_param"] = settings.n_samples_per_param + for section, overrides in (generator_config or {}).items(): + if section not in gen or not isinstance(overrides, dict): + raise ValueError(f"unknown or non-nested generator override: {section}") + gen[section].update(deepcopy(overrides)) + gen["pipeline"]["n_cpus"] = 1 + # Both stale spelling and unsafe displacement are excluded explicitly. + gen["estimator"].pop("kde_displace_t", None) + gen["estimator"].update(type=estimator, displace_t=False) + if estimator not in ("kde", "pyddm"): + raise ValueError("estimator must be kde or pyddm") + if estimator == "pyddm" and ( + cfg.get("n_particles", 1) != 1 + or cfg["nchoices"] != 2 + or "python_simulator" in cfg.get("tags", []) + ): + raise ValueError( + "PyDDM requires a single-particle two-choice diffusion; see ssms #443" + ) + output = Path(out_dir).resolve() + if output.exists() and any(output.iterdir()): + raise FileExistsError("out_dir must be empty: never reuse a prior certificate") + output.mkdir(parents=True, exist_ok=True) + gen["output"]["folder"] = str(output / "training_data") + if estimator == "kde": + pipeline = GuardedSimulationPipeline( + gen, cfg, KDEEstimatorBuilder, ResampleMixtureStrategy + ) + else: + from ssms.dataset_generators.pipelines.pipeline_factory import ( + create_data_generation_pipeline, + ) + + pipeline = create_data_generation_pipeline(gen, cfg) + generator = TrainingDataGenerator(config=pipeline) + start = time.monotonic() + old_rng = np.random.get_state() + np.random.seed(seed) + files, row_counts = [], [] + try: + with torch.random.fork_rng(): + torch.manual_seed(seed) + for i in range(settings.n_files): + data = generator.generate_data_training(save=False) + rows = data["lan_data"].shape[0] + if ( + rows == 0 + or not np.isfinite(data["lan_data"]).all() + or not np.isfinite(data["lan_labels"]).all() + ): + raise ValueError( + "generator returned empty or nonfinite training data" + ) + path = output / "training_data" / f"part-{i:03}.pickle" + with path.open("wb") as stream: + cloudpickle.dump(data, stream) + files.append(str(path)) + row_counts.append(rows) + train = ( + deepcopy(train_config_mlp) + | {"n_epochs": settings.n_epochs} + | (train_config or {}) + ) + batch = batch_divisor( + int(np.gcd.reduce(row_counts)), int(train["cpu_batch_size"]) + ) + train["cpu_batch_size"] = batch + train_dl, valid_dl, width = make_train_valid_dataloaders( + files, + batch_size=batch, + network_type="lan", + num_workers=0, + pin_memory=False, + label_lower_bound=-16.11809565095832, + ) + net_config = deepcopy(network_config_mlp) | (network_config or {}) + if ( + net_config.get("train_output_type") != "logprob" + or net_config["layer_sizes"][-1] != 1 + ): + raise ValueError("recipe requires one log-density output") + net = TorchMLPFactory(net_config, input_dim=width, network_type="lan") + trainer = ModelTrainerTorchMLP( + net, train, train_dl, valid_dl, pin_memory=False, seed=seed + ) + trainer.train_and_evaluate( + output_folder=output, + output_file_id=model, + run_id=str(seed), + mlflow_on=False, + save_outputs=True, + verbose=0, + ) + path = output / f"{model}_lan_{seed}_model.onnx" + net.eval() + validation = { + g: gates.result(False, skipped=True, reason="validation disabled") + for g in ("G1", "G2", "G3", "G4", "G5") + } + if validate: + validation["G1"] = gates.checked( + gates.gate_structure, path, len(cfg["params"]) + 2 + ) + if validation["G1"]["passed"]: + predict = gates.ONNXPredictor(path) + probe = data["lan_data"][:1000] + validation["G2"] = gates.checked( + gates.gate_parity, predict, net, probe + ) + box = np.array(list(cfg["param_bounds_dict"].values())) + rng = np.random.default_rng(seed + 7000003) + points = box[:, 0] + (box[:, 1] - box[:, 0]) * rng.uniform( + 0.2, 0.8, (5, len(box)) + ) + sim_args = { + "max_t": gen["simulator"]["max_t"], + "delta_t": gen["simulator"]["delta_t"], + } + fresh = gates.checked( + lambda: gates.simulate( + cfg, points[0], 256, seed + 8000003, **sim_args + ) + ) + # checked() returns either the simulation or a failed gate. + validation["G3"] = ( + gates.checked(gates.gate_hssm, path, cfg, fresh) + if "rts" in fresh + else fresh + ) + validation["G4"] = gates.checked( + gates.gate_density, + predict, + cfg, + points, + n_sim=settings.validation_n, + seed=seed + 9000003, + **sim_args, + ) + validation["G5"] = gates.checked( + gates.gate_gradient, + path, + predict, + cfg, + points, + n_sim=settings.validation_n, + seed=seed + 10000003, + **sim_args, + ) + else: + for g in ("G2", "G3", "G4", "G5"): + validation[g] = gates.result( + False, skipped=True, reason="G1 failed" + ) + finally: + np.random.set_state(old_rng) + manifest = { + "schema": "lanfactory-ssms-recipe-1", + "created": datetime.now(UTC).isoformat(), + "model": model, + "preset": preset, + "settings": asdict(settings), + "seed": seed, + "production_validated": False, + "fixed_parameters": dict(fixed_parameters or {}), + "model_config": _describe(cfg), + "generator_config": gen, + "train_config": train, + "network_config": net_config, + "source": _source_revision(), + "versions": { + p: importlib.metadata.version(p) + for p in ( + "lanfactory", + "ssm-simulators", + "torch", + "numpy", + "pandas", + "onnx", + "onnxruntime", + ) + }, + "elapsed_seconds": time.monotonic() - start, + "files": [ + {"name": Path(f).name, "sha256": _sha(f), "rows": n} + for f, n in zip(files, row_counts, strict=True) + ], + "onnx": {"name": path.name, "sha256": _sha(path)}, + "filter_guard": { + "accepted": getattr(pipeline, "accepted", None), + "rejected": getattr(pipeline, "rejected", None), + "policy": "strict canonical filters plus no omissions/horizon hits", + }, + "validation": validation, + } + manifest["model_config_sha256"] = hashlib.sha256( + json.dumps(manifest["model_config"], sort_keys=True).encode() + ).hexdigest() + for dependency in ("hssm", "jax", "jaxonnxruntime"): + try: + manifest["versions"][dependency] = importlib.metadata.version(dependency) + except importlib.metadata.PackageNotFoundError: + manifest["versions"][dependency] = None + artifact = LANArtifact(path, None, validation, manifest, output) + if artifact.validated: + artifact.hssm_model_config = gates.hssm_config(cfg) + _write(output / "model_config.json", artifact.hssm_model_config) + manifest["validated"] = artifact.validated + _write(output / "validation.json", validation) + _write(output / "manifest.json", manifest) + return artifact diff --git a/src/lanfactory/recipes/guards.py b/src/lanfactory/recipes/guards.py new file mode 100644 index 0000000..32fa6ee --- /dev/null +++ b/src/lanfactory/recipes/guards.py @@ -0,0 +1,123 @@ +"""Local guards for ssms 0.16's filter and runtime-config contracts. + +No process-wide patches: the recipe injects this pipeline into the public +TrainingDataGenerator. Remove the filter compatibility code once #432 ships; +the regression cases should remain. +""" + +from copy import deepcopy + +import numpy as np +from ssms.dataset_generators.pipelines.simulation_pipeline import SimulationPipeline + + +def normalize_model_config(config, fixed_parameters=None): + """Copy and validate numeric training bounds in the simulator's param order.""" + cfg = deepcopy(config) + params = cfg["params"] + if not params or len(set(params)) != len(params): + raise ValueError("params must be nonempty and unique") + bounds = cfg.get("param_bounds") + if bounds is None: + bounds = cfg.get("param_bounds_dict") + if not isinstance(bounds, dict): + if ( + bounds is None + or len(bounds) != 2 + or any(len(row) != len(params) for row in bounds) + ): + raise ValueError("param_bounds must have exactly two rows in params order") + bounds = dict(zip(params, zip(*bounds, strict=True), strict=True)) + if set(bounds) != set(params): + raise ValueError("training bounds must name exactly the simulator parameters") + fixed = dict(fixed_parameters or {}) + if set(fixed) - set(params): + raise ValueError("fixed_parameters names unknown parameters") + normalized = {} + for p in params: + try: + lo, hi = map(float, bounds[p]) + except (TypeError, ValueError) as err: + raise ValueError(f"{p}: recipe requires finite numeric bounds") from err + if not np.isfinite([lo, hi]).all() or lo >= hi: + raise ValueError(f"{p}: bounds must be finite with lower < upper") + if p in fixed: + value = float(fixed[p]) + if not lo <= value <= hi: + raise ValueError(f"{p}: fixed value outside model bounds") + lo = hi = value + normalized[p] = (lo, hi) + if len(fixed) == len(params): + raise ValueError("at least one parameter must be free") + cfg["param_bounds_dict"] = normalized + cfg["param_bounds"] = [[normalized[p][i] for p in params] for i in (0, 1)] + cfg["n_params"] = len(params) + choices = cfg["choices"] + if len(choices) < 2 or len(set(choices)) != len(choices): + raise ValueError("recipe requires at least two distinct RT/choice outcomes") + cfg["nchoices"] = len(choices) + return cfg + + +def simulation_issues(simulations, max_t): + """Reject censored, clamped, nonfinite or nonpositive training samples. + + This conservative test treats max_t as a bound on decision time and uses + min(t,tT) for two-onset models. It also rejects RTs beyond the horizon for + kernels that ignore max_t. It does not resolve ssms #404 globally. + """ + rt = np.asarray(simulations["rts"]).ravel() + meta = simulations["metadata"] + onset = ( + min(float(np.min(meta.get("t", 0))), float(np.min(meta["tT"]))) + if "tT" in meta + else float(np.min(meta.get("t", 0))) + ) + choices = np.asarray(simulations["choices"]).ravel() + return { + "invalid_rt": int(np.count_nonzero(~np.isfinite(rt) | (rt <= 0))), + "at_or_past_horizon": int(np.count_nonzero(rt >= max_t + onset - 1e-6)), + "invalid_choice": int( + np.count_nonzero(~np.isin(choices, meta["possible_choices"])) + ), + "n_samples": int(rt.size), + } + + +class GuardedSimulationPipeline(SimulationPipeline): + """Apply the canonical strict filters before fitting any KDE.""" + + def _is_valid_simulation(self, simulations): + filters = self.generator_config["pipeline"]["simulation_filters"] + issues = simulation_issues( + simulations, self.generator_config["simulator"]["max_t"] + ) + keep = issues["n_samples"] > 0 and not any( + issues[k] for k in ("invalid_rt", "at_or_past_horizon", "invalid_choice") + ) + rt = np.asarray(simulations["rts"]).ravel() + choice = np.asarray(simulations["choices"]).ravel() + for c in simulations["metadata"]["possible_choices"]: + values = rt[choice == c] + if not values.size: + keep = False + continue + unique, counts = np.unique(values, return_counts=True) + mode = float(unique[np.argmax(counts)]) + keep = keep and ( + mode < filters.get("mode", np.inf) + and float(values.mean()) <= filters.get("mean_rt", np.inf) + and float(values.std()) > filters.get("std", -np.inf) + and float(counts.max() / values.size) <= filters.get("mode_cnt_rel", 1) + and values.size > filters.get("choice_cnt", -np.inf) + ) + self.rejected = getattr(self, "rejected", 0) + int(not keep) + self.accepted = getattr(self, "accepted", 0) + int(keep) + self.consecutive_rejections = ( + 0 if keep else getattr(self, "consecutive_rejections", 0) + 1 + ) + if self.consecutive_rejections > 100: + raise RuntimeError( + "100 consecutive rejected simulations: narrow the training box or extend max_t" + ) + return bool(keep), np.array(list(issues.values()), dtype=np.float32) diff --git a/src/lanfactory/recipes/validation.py b/src/lanfactory/recipes/validation.py new file mode 100644 index 0000000..9465501 --- /dev/null +++ b/src/lanfactory/recipes/validation.py @@ -0,0 +1,353 @@ +"""Small, fail-closed LAN checks; toy runs may legitimately fail them. + +G5 tests both implementation derivatives and sensitivity of independently +simulated densities. Finite differences of the network alone cannot validate +the latter. Production recovery/calibration remains a separate cluster job. +""" + +import importlib.util + +import numpy as np + +from .guards import simulation_issues + + +def result(passed, **details): + return {"passed": bool(passed), **details} + + +def checked(function, *args, **kwargs): + try: + return function(*args, **kwargs) + except Exception as err: + return result(False, error=f"{type(err).__name__}: {err}") + + +class ONNXPredictor: + """Evaluate a concrete single-trial graph without changing its semantics.""" + + def __init__(self, path): + import onnxruntime as ort + + options = ort.SessionOptions() + options.intra_op_num_threads = 1 + options.inter_op_num_threads = 1 + self.session = ort.InferenceSession( + str(path), options, providers=["CPUExecutionProvider"] + ) + self.input = self.session.get_inputs()[0] + + def __call__(self, rows): + rows = np.asarray(rows, dtype=np.float32) + return np.array( + [ + np.asarray( + self.session.run( + None, {self.input.name: row.reshape(self.input.shape)} + )[0] + ).item() + for row in rows + ] + ) + + +def gate_structure(path, width): + from lanfactory.onnx.contract import assert_single_trial_contract + + metadata = assert_single_trial_contract(path, expected_input_width=width) + predictor = ONNXPredictor(path) + if ( + len(predictor.session.get_inputs()) != 1 + or len(predictor.session.get_outputs()) != 1 + ): + return result(False, error="expected exactly one input and output") + value = predictor(np.zeros((1, width))) + return result(np.isfinite(value).all(), **metadata) + + +def gate_parity(predict, network, rows, atol=1e-4): + import torch + + network.eval() + with torch.no_grad(): + expected = ( + network( + torch.tensor( + rows, dtype=torch.float32, device=next(network.parameters()).device + ) + ) + .cpu() + .numpy() + .ravel() + ) + observed = predict(rows) + error = float(np.max(np.abs(expected - observed))) + return result( + np.isfinite(observed).all() and error <= atol, + max_abs_error=error, + atol=atol, + n_rows=len(rows), + ) + + +def hssm_config(config): + bounds = config["param_bounds_dict"] + fixed = {p: lo for p, (lo, hi) in bounds.items() if lo == hi} + out = { + "list_params": list(config["params"]), + "choices": list(config["choices"]), + "bounds": {p: list(b) for p, b in bounds.items() if p not in fixed}, + "default_priors": fixed, + "backend": "jax", + "response": ["rt", "response"], + } + if config.get("ndt_edge_shift") is not None: + out["ndt_edge_shift"] = config["ndt_edge_shift"] + return out + + +def simulate(config, theta, n, seed, max_t, delta_t): + from ssms import Simulator + + out = Simulator(config).simulate( + dict(zip(config["params"], theta, strict=True)), + n_samples=n, + random_state=int(seed), + max_t=max_t, + delta_t=delta_t, + ) + issues = simulation_issues(out, max_t) + if any(issues[k] for k in ("invalid_rt", "at_or_past_horizon", "invalid_choice")): + raise ValueError(f"fresh simulation has invalid/horizon observations: {issues}") + if set(np.asarray(out["choices"]).ravel()) != set(config["choices"]): + raise ValueError("fresh simulation is missing a possible choice") + return out + + +def make_kde(simulations): + from ssms.dataset_generators.likelihood_estimators.kde_estimator import ( + KDELikelihoodEstimator, + ) + + estimator = KDELikelihoodEstimator(displace_t=False) + estimator.fit(simulations) + return estimator + + +def gate_hssm(path, config, simulations): + if importlib.util.find_spec("hssm") is None: + return result(False, skipped=True, reason="hssm is not installed") + import hssm + import pandas as pd + + data = pd.DataFrame( + { + "rt": np.asarray(simulations["rts"]).ravel()[:64], + "response": np.asarray(simulations["choices"]).ravel()[:64], + } + ) + model = hssm.HSSM( + data, + model=config["name"], + loglik=str(path), + loglik_kind="approx_differentiable", + model_config=hssm_config(config), + p_outlier=0.0, + ) + pymc_model = model.pymc_model + value = float(pymc_model.compile_logp()(pymc_model.initial_point())) + return result(np.isfinite(value), initial_logp=value, n_trials=len(data)) + + +def hellinger(a, b, grid): + return float( + np.sqrt(max(0, np.trapezoid((np.sqrt(a) - np.sqrt(b)) ** 2, grid) / 2)) + ) + + +def gate_density( + predict, + config, + points, + *, + n_sim, + seed, + max_t, + delta_t, + mass_range=(0.9, 1.1), + max_hellinger=0.15, + max_ratio=3.0, +): + records = [] + for i, theta in enumerate(points): + draws = [ + simulate(config, theta, n_sim, seed + 1009 * i + j, max_t, delta_t) + for j in (0, 1) + ] + kdes = [make_kde(draw) for draw in draws] + # Dense where observations occur, plus the entire remaining horizon. + upper = min( + max_t, float(np.quantile(np.asarray(draws[0]["rts"]), 0.9995)) * 1.1 + ) + grid = np.unique( + np.r_[np.linspace(1e-5, upper, 400), np.linspace(upper, max_t, 80)] + ) + mass, distance2, floor2 = 0.0, 0.0, 0.0 + per_choice = [] + for c in config["choices"]: + choices = np.full(grid.size, c) + reference, replicate = [np.exp(kde.evaluate(grid, choices)) for kde in kdes] + if not np.isfinite(reference).all() or not np.isfinite(replicate).all(): + return result(False, error="nonfinite reference density") + rows = np.column_stack([np.tile(theta, (grid.size, 1)), grid, choices]) + logp = predict(rows) + if not np.isfinite(logp).all() or np.max(logp) > 80: + return result(False, error="nonfinite or overflowing network density") + density = np.exp(logp) + m = float(np.trapezoid(density, grid)) + h = hellinger(density, reference, grid) + floor = hellinger(reference, replicate, grid) + mass += m + distance2 += h**2 + floor2 += floor**2 + per_choice.append({"choice": int(c), "mass": m, "hellinger": h}) + h, floor = np.sqrt(distance2), np.sqrt(floor2) + ratio = float(h / max(floor, 1e-6)) + # Both absolute and noise-relative errors must be small. + passed = ( + mass_range[0] <= mass <= mass_range[1] + and h <= max_hellinger + and ratio <= max_ratio + ) + records.append( + { + "theta": list(map(float, theta)), + "mass": mass, + "hellinger": float(h), + "sampling_floor": float(floor), + "ratio": ratio, + "passed": bool(passed), + "choices": per_choice, + } + ) + return result( + all(row["passed"] for row in records), + points=records, + n_sim=n_sim, + mass_range=list(mass_range), + max_hellinger=max_hellinger, + max_ratio=max_ratio, + ) + + +def gate_gradient( + path, + predict, + config, + points, + *, + n_sim, + seed, + max_t, + delta_t, + autodiff_atol=0.01, + fidelity_atol=0.5, + fidelity_rtol=0.35, + max_reference_noise=0.5, +): + if importlib.util.find_spec("hssm") is None: + return result(False, skipped=True, reason="hssm is not installed") + import jax + import jax.numpy as jnp + from hssm.distribution_utils.onnx import make_jax_logp_funcs_from_onnx + + logp, _ = make_jax_logp_funcs_from_onnx( + path, [False] * len(config["params"]), return_jit=False + ) + gradients = jax.jit(jax.jacrev(lambda theta, obs: logp(obs, *theta), argnums=0)) + spans = np.array([hi - lo for lo, hi in config["param_bounds_dict"].values()]) + free = np.flatnonzero(spans > 0) + records = [] + for i, theta in enumerate(points): + draws = simulate(config, theta, n_sim, seed + i * 1009, max_t, delta_t) + rts, choices = [np.asarray(draws[k]).ravel() for k in ("rts", "choices")] + obs = np.array( + [ + [np.quantile(rts[choices == c], q), c] + for c in config["choices"] + for q in (0.35, 0.65) + ] + ) + auto = np.asarray(gradients(jnp.asarray(theta), jnp.asarray(obs))).reshape( + len(obs), -1 + ) + own, reference, noise = [], [], [] + for p in free: + tiny = max(1e-3, spans[p] * 1e-3) + plus, minus = np.array(theta), np.array(theta) + plus[p] += tiny + minus[p] -= tiny + own.append( + ( + predict(np.column_stack([np.tile(plus, (len(obs), 1)), obs])) + - predict(np.column_stack([np.tile(minus, (len(obs), 1)), obs])) + ) + / (2 * tiny) + * spans[p] + ) + step = 0.04 * spans[p] + plus[p], minus[p] = theta[p] + step, theta[p] - step + replicas = [] + for j in (0, 1): + # Common random numbers at +/- step; a fresh independent pair + # measures the uncertainty of the reference derivative. + pair_seed = seed + 100_003 + i * 1009 + j + pdfs = [ + make_kde( + simulate(config, point, n_sim, pair_seed, max_t, delta_t) + ).evaluate(obs[:, 0], obs[:, 1]) + for point in (plus, minus) + ] + replicas.append((pdfs[0] - pdfs[1]) / (2 * step) * spans[p]) + reference.append(np.mean(replicas, axis=0)) + noise.append(np.abs(replicas[0] - replicas[1]) / 2) + own, reference, noise = [np.asarray(a).T for a in (own, reference, noise)] + scaled_auto = auto[:, free] * spans[free] + implementation_error = float(np.max(np.abs(own - scaled_auto))) + reference_noise = float(np.sqrt(np.mean(noise**2))) + error = float(np.sqrt(np.mean((scaled_auto - reference) ** 2))) + tolerance = float( + fidelity_atol + fidelity_rtol * np.sqrt(np.mean(reference**2)) + ) + finite = np.isfinite( + np.r_[scaled_auto.ravel(), own.ravel(), reference.ravel(), noise.ravel()] + ).all() + passed = ( + finite + and implementation_error <= autodiff_atol + and reference_noise <= max_reference_noise + and error <= tolerance + ) + records.append( + { + "theta": list(map(float, theta)), + "passed": bool(passed), + "autodiff_max_error": implementation_error, + "reference_rms_error": error, + "reference_rms_noise": reference_noise, + "fidelity_tolerance": tolerance, + "parameters": [config["params"][p] for p in free], + "autodiff_scaled": scaled_auto.tolist(), + "reference_scaled": reference.tolist(), + } + ) + return result( + all(row["passed"] for row in records), + points=records, + n_sim=n_sim, + autodiff_atol=autodiff_atol, + max_reference_noise=max_reference_noise, + fidelity_atol=fidelity_atol, + fidelity_rtol=fidelity_rtol, + reference="paired-seed finite differences of fresh log-RT KDE; two independent pairs", + ) diff --git a/tests/test_recipe_gradient.py b/tests/test_recipe_gradient.py new file mode 100644 index 0000000..995288c --- /dev/null +++ b/tests/test_recipe_gradient.py @@ -0,0 +1,79 @@ +"""A graph can have correct autodiff while representing the wrong likelihood.""" + +import numpy as np +import pytest +import torch + +from lanfactory.recipes import validation + + +class Gaussian(torch.nn.Module): + def __init__(self, correct): + super().__init__() + self.correct = correct + self.projection = torch.nn.Linear(4, 1) + with torch.no_grad(): + self.projection.weight.copy_( + torch.tensor([[-5.0, 0.0, 1.0, 0.0]]) if correct else torch.zeros(1, 4) + ) + self.projection.bias.fill_(-2.0 if correct else 0.0) + + def forward(self, x): + projected = self.projection(x) + if self.correct: + return -0.5 * projected**2 - 1.612085714 + return projected + + +@pytest.mark.parametrize("correct", [False, True]) +def test_gradient_fidelity_is_separate_from_autodiff(correct, monkeypatch, tmp_path): + pytest.importorskip("hssm") + path = tmp_path / "density.onnx" + network = Gaussian(correct) + torch.onnx.export(network, torch.zeros(1, 4), str(path), dynamo=False) + + def simulate(config, theta, *args, **kwargs): + return { + "theta": theta, + "rts": np.array([1.0, 2.0, 3.0] * 2), + "choices": np.array([0, 0, 0, 1, 1, 1]), + } + + class KDE: + def __init__(self, draws): + self.v = draws["theta"][0] + + def evaluate(self, rt, choices): + return -0.5 * (rt - (5 * self.v + 2)) ** 2 - 1.612085714 + + monkeypatch.setattr(validation, "simulate", simulate) + monkeypatch.setattr(validation, "make_kde", KDE) + cfg = { + "params": ["v", "fixed"], + "choices": [0, 1], + "param_bounds_dict": {"v": [-1.0, 1.0], "fixed": [0.2, 0.2]}, + } + gate = validation.gate_gradient( + path, + validation.ONNXPredictor(path), + cfg, + [np.array([0.0, 0.2])], + n_sim=6, + seed=1, + max_t=20.0, + delta_t=0.001, + ) + assert gate["points"][0]["autodiff_max_error"] < 0.01 + assert gate["passed"] is correct + + +def test_export_parity_rejects_a_different_network(tmp_path): + path = tmp_path / "density.onnx" + network = torch.nn.Linear(4, 1) + torch.onnx.export(network, torch.zeros(1, 4), str(path), dynamo=False) + with torch.no_grad(): + network.bias.add_(1) + gate = validation.gate_parity( + validation.ONNXPredictor(path), network, np.ones((5, 4)) + ) + assert gate["passed"] is False diff --git a/tests/test_ssms_recipe.py b/tests/test_ssms_recipe.py new file mode 100644 index 0000000..f9b41b6 --- /dev/null +++ b/tests/test_ssms_recipe.py @@ -0,0 +1,238 @@ +"""Regressions for the ssms recipe's data and validation boundaries.""" + +from copy import deepcopy + +import numpy as np +import pytest +from ssms.config import ModelConfigBuilder, get_lan_kde_config + +from lanfactory.recipes.from_ssms import LANArtifact, batch_divisor, train_lan_for_model +from lanfactory.recipes.guards import ( + GuardedSimulationPipeline, + normalize_model_config, + simulation_issues, +) +from lanfactory.recipes.validation import gate_density, hssm_config + + +def fixture_sim(rts=None, choices=None): + return { + "rts": np.array([0.3, 0.5, 0.7, 0.4, 0.6, 0.8] if rts is None else rts), + "choices": np.array([0, 0, 0, 1, 1, 1] if choices is None else choices), + "metadata": {"possible_choices": [0, 1], "t": 0.1, "max_t": 20.0}, + } + + +def pipeline(filters=None): + obj = GuardedSimulationPipeline.__new__(GuardedSimulationPipeline) + obj.generator_config = get_lan_kde_config() + if filters is not None: + obj.generator_config["pipeline"]["simulation_filters"] = filters + return obj + + +@pytest.mark.parametrize( + "sim", + [ + fixture_sim([20.1] * 6), + fixture_sim(choices=[0] * 6), + fixture_sim([0.4] * 3 + [0.6] * 3), + fixture_sim([-0.999, 0.5, 0.7, 0.4, 0.6, 0.8]), + fixture_sim([float("nan"), 0.5, 0.7, 0.4, 0.6, 0.8]), + ], +) +def test_canonical_filters_reject_degenerate_simulations(sim): + assert not pipeline()._is_valid_simulation(sim)[0] + + +@pytest.mark.parametrize( + "filters", + [ + {"mode": 0.3}, + {"std": np.std([0.3, 0.5, 0.7])}, + {"choice_cnt": 3}, + {"mean_rt": 0.1}, + {"mode_cnt_rel": 0.2}, + ], +) +def test_canonical_key_and_strict_thresholds(filters): + assert not pipeline(filters)._is_valid_simulation(fixture_sim())[0] + + +def test_valid_simulation_and_guards_are_local(): + assert pipeline()._is_valid_simulation(fixture_sim())[0] + from ssms.dataset_generators.pipelines.simulation_pipeline import SimulationPipeline + + assert ( + SimulationPipeline._is_valid_simulation + is not GuardedSimulationPipeline._is_valid_simulation + ) + + +@pytest.mark.parametrize("rt", [-999.0, 0.0, np.inf, 20.1, 21.0]) +def test_horizon_policy_rejects_censor_clamp_and_ignored_horizon(rt): + issues = simulation_issues(fixture_sim([rt] * 6), 20.0) + assert issues["invalid_rt"] + issues["at_or_past_horizon"] > 0 + + +def test_registered_bounds_are_normalized_without_mutation(monkeypatch): + from ssms.config import get_model_registry, register_model_config + + config = ModelConfigBuilder.from_model("angle") + config["name"] = "recipe_runtime_angle" + config.pop("param_bounds_dict", None) + before = deepcopy(config) + registry = get_model_registry() + monkeypatch.setattr(registry, "_configs", dict(registry._configs)) + register_model_config(config["name"], config) + runtime = ModelConfigBuilder.from_model(config["name"]) + normalized = normalize_model_config(runtime) + assert list(normalized["param_bounds_dict"]) == config["params"] + assert "param_bounds_dict" not in config + assert config == before + + +def test_bounds_from_raw_source_override_stale_derived_bounds(): + cfg = ModelConfigBuilder.from_model("ddm") + cfg["param_bounds"][0][0], cfg["param_bounds"][1][0] = -1.0, 1.0 + normalized = normalize_model_config(cfg) + assert normalized["param_bounds_dict"]["v"] == (-1.0, 1.0) + + +@pytest.mark.parametrize( + "change", + [ + {"param_bounds": [[0.0], [1.0]]}, + {"param_bounds": {"v": (-1.0, 1.0)}}, + {"param_bounds": [[-1.0, 0.3, 0.1, 0.0], [float("inf"), 3.0, 0.9, 2.0]]}, + {"param_bounds": [[-1.0, 0.3, 0.1, 0.0], [-1.0, 3.0, 0.9, 2.0]]}, + ], +) +def test_malformed_bounds_fail_before_training(change): + with pytest.raises(ValueError): + normalize_model_config(ModelConfigBuilder.from_model("ddm") | change) + + +def test_fixed_parameters_are_fixed_hssm_priors(): + cfg = normalize_model_config( + ModelConfigBuilder.from_model("ddm"), {"a": 1.0, "z": 0.5, "t": 0.2} + ) + out = hssm_config(cfg) + assert out["list_params"] == cfg["params"] + assert out["bounds"] == {"v": [-3.0, 3.0]} + assert out["default_priors"] == {"a": 1.0, "z": 0.5, "t": 0.2} + + +def test_bad_fixed_value_and_all_fixed_are_rejected(): + cfg = ModelConfigBuilder.from_model("ddm") + with pytest.raises(ValueError, match="outside"): + normalize_model_config(cfg, {"v": 100}) + with pytest.raises(ValueError, match="at least one"): + normalize_model_config(cfg, dict(zip(cfg["params"], cfg["default_params"]))) + + +def test_batch_divisor(): + with pytest.warns(UserWarning, match="using 250"): + assert batch_divisor(1000, 256) == 250 + assert batch_divisor(4096, 256) == 256 + with pytest.raises(ValueError): + batch_divisor(0, 256) + + +def test_production_needs_explicit_opt_in(tmp_path): + with pytest.raises(ValueError, match="production requires"): + train_lan_for_model("ddm", tmp_path, preset="production") + assert not list(tmp_path.iterdir()) + + +def test_skipped_or_missing_gate_cannot_certify(tmp_path): + passing = {g: {"passed": True} for g in ("G1", "G2", "G3", "G4", "G5")} + artifact = LANArtifact(tmp_path / "net.onnx", {}, passing, {}, tmp_path) + assert artifact.validated + passing["G5"]["skipped"] = True + assert not artifact.validated + del passing["G5"] + assert not artifact.validated + + +def test_constant_bad_density_cannot_pass(monkeypatch): + from lanfactory.recipes import validation + + monkeypatch.setattr(validation, "simulate", lambda *a, **kw: fixture_sim()) + + class KDE: + def evaluate(self, rt, choice): + return np.full(len(rt), -np.log(2 * 20)) + + monkeypatch.setattr(validation, "make_kde", lambda x: KDE()) + cfg = {"choices": [0, 1]} + check = gate_density( + lambda rows: np.zeros(len(rows)), + cfg, + [np.array([1.0])], + n_sim=6, + seed=1, + max_t=20.0, + delta_t=0.001, + ) + assert check["passed"] is False + + +def test_nonfinite_reference_cannot_pass(monkeypatch): + from lanfactory.recipes import validation + + monkeypatch.setattr(validation, "simulate", lambda *a, **kw: fixture_sim()) + + class KDE: + def evaluate(self, rt, choice): + return np.full(len(rt), np.nan) + + monkeypatch.setattr(validation, "make_kde", lambda x: KDE()) + check = gate_density( + lambda rows: np.zeros(len(rows)), + {"choices": [0, 1]}, + [np.array([1.0])], + n_sim=6, + seed=1, + max_t=20.0, + delta_t=0.001, + ) + assert check["passed"] is False + assert "nonfinite reference" in check["error"] + + +def test_nonfinite_failed_metrics_remain_strict_json(tmp_path): + import json + + from lanfactory.recipes.from_ssms import _write + + path = tmp_path / "failure.json" + _write(path, {"passed": False, "error": np.array([np.nan, np.inf])}) + assert json.loads(path.read_text())["error"] == [None, None] + + +@pytest.mark.slow +def test_toy_recipe_runs_real_runtime_angle_training_without_certificate(tmp_path): + cfg = ModelConfigBuilder.from_model("angle") + cfg["name"] = "recipe_toy_angle" + cfg.pop("param_bounds_dict", None) + artifact = train_lan_for_model( + cfg["name"], + tmp_path, + model_config=cfg, + fixed_parameters={"a": 1.0, "z": 0.5, "t": 0.2, "theta": 0.2}, + generator_config={ + "pipeline": {"n_parameter_sets": 4}, + "training": {"n_samples_per_param": 64}, + }, + train_config={"n_epochs": 1}, + validate=False, + ) + assert artifact.onnx_path.exists() + assert artifact.hssm_model_config is None + assert not artifact.validated + assert not (tmp_path / "model_config.json").exists() + assert len(artifact.manifest["files"]) == 2 + from lanfactory.recipes.validation import gate_structure + + assert gate_structure(artifact.onnx_path, len(cfg["params"]) + 2)["passed"] From 21fe79af4b91a5851f378c414a7e8126ec75de5c Mon Sep 17 00:00:00 2001 From: Francesco Muia Date: Tue, 24 Nov 2026 13:29:15 +0100 Subject: [PATCH 2/5] Document recipe API and CLI contracts for CI --- docs/api/cli.md | 20 +++++++++++++++++++- docs/api/recipes.md | 10 ++++++++++ mkdocs.yml | 1 + src/lanfactory/cli/lan_from_ssms.py | 10 +++++----- src/lanfactory/derive/integrate.py | 2 +- tests/test_docs_api_reference.py | 4 ++++ 6 files changed, 40 insertions(+), 7 deletions(-) create mode 100644 docs/api/recipes.md diff --git a/docs/api/cli.md b/docs/api/cli.md index 4d57009..120616d 100644 --- a/docs/api/cli.md +++ b/docs/api/cli.md @@ -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 diff --git a/docs/api/recipes.md b/docs/api/recipes.md new file mode 100644 index 0000000..0c520ce --- /dev/null +++ b/docs/api/recipes.md @@ -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 diff --git a/mkdocs.yml b/mkdocs.yml index 6ffd603..e550cb1 100755 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -35,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 diff --git a/src/lanfactory/cli/lan_from_ssms.py b/src/lanfactory/cli/lan_from_ssms.py index 71a5ba4..72e4da1 100644 --- a/src/lanfactory/cli/lan_from_ssms.py +++ b/src/lanfactory/cli/lan_from_ssms.py @@ -15,17 +15,17 @@ def main( model: str = typer.Option(...), out: Path = typer.Option(...), - preset: str = "toy", + 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 = 0, - estimator: str = "kde", - validate: bool = True, - allow_production: bool = False, + 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: diff --git a/src/lanfactory/derive/integrate.py b/src/lanfactory/derive/integrate.py index 3cb1849..cd5df98 100644 --- a/src/lanfactory/derive/integrate.py +++ b/src/lanfactory/derive/integrate.py @@ -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. diff --git a/tests/test_docs_api_reference.py b/tests/test_docs_api_reference.py index 865b317..6efae4c 100644 --- a/tests/test_docs_api_reference.py +++ b/tests/test_docs_api_reference.py @@ -120,6 +120,10 @@ def test_config_exports_are_referenced() -> None: _assert_documented("src/lanfactory/config/__init__.py", "docs/api/config.md") +def test_recipe_exports_are_referenced() -> None: + _assert_documented("src/lanfactory/recipes/__init__.py", "docs/api/recipes.md") + + def test_hf_exports_are_referenced() -> None: _assert_documented("src/lanfactory/hf/__init__.py", "docs/api/hf.md") From 2eee26b5d5d3ae90f9f5c0bd07715997f42da61f Mon Sep 17 00:00:00 2001 From: Francesco Muia Date: Tue, 24 Nov 2026 13:29:38 +0100 Subject: [PATCH 3/5] Format recipe CLI preset option --- src/lanfactory/cli/lan_from_ssms.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/lanfactory/cli/lan_from_ssms.py b/src/lanfactory/cli/lan_from_ssms.py index 72e4da1..0ec6bec 100644 --- a/src/lanfactory/cli/lan_from_ssms.py +++ b/src/lanfactory/cli/lan_from_ssms.py @@ -15,7 +15,9 @@ def main( model: str = typer.Option(...), out: Path = typer.Option(...), - preset: str = typer.Option("toy", help="toy, dev or explicitly authorized production"), + 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" ), From 83f625b2ee7bd828160350de423c0c5ee894cd44 Mon Sep 17 00:00:00 2001 From: Francesco Muia Date: Tue, 24 Nov 2026 13:52:56 +0100 Subject: [PATCH 4/5] Exercise optional HSSM recipe gates in focused CPU CI --- .github/workflows/run_tests.yml | 37 ++++++++++++ tests/test_ssms_recipe.py | 100 ++++++++++++++++++++++++++++++++ 2 files changed, 137 insertions(+) diff --git a/.github/workflows/run_tests.yml b/.github/workflows/run_tests.yml index e9a31c6..3b2fe0e 100644 --- a/.github/workflows/run_tests.yml +++ b/.github/workflows/run_tests.yml @@ -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 diff --git a/tests/test_ssms_recipe.py b/tests/test_ssms_recipe.py index f9b41b6..646a4b7 100644 --- a/tests/test_ssms_recipe.py +++ b/tests/test_ssms_recipe.py @@ -145,6 +145,43 @@ def test_production_needs_explicit_opt_in(tmp_path): assert not list(tmp_path.iterdir()) +@pytest.mark.parametrize( + "kwargs,match", + [ + ({"preset": "unknown"}, "unknown preset"), + ({"seed": -1}, "nonnegative"), + ({"generator_config": {"missing": {}}}, "generator override"), + ({"generator_config": {"pipeline": 1}}, "generator override"), + ({"estimator": "unknown"}, "estimator must"), + ( + { + "estimator": "pyddm", + "model_config": ModelConfigBuilder.from_model("race_3"), + }, + "name must agree", + ), + ], +) +def test_invalid_recipe_requests_fail_without_artifacts(tmp_path, kwargs, match): + with pytest.raises(ValueError, match=match): + train_lan_for_model("ddm", tmp_path, **kwargs) + assert not list(tmp_path.iterdir()) + + +def test_pyddm_rejects_multi_accumulator_before_creating_output(tmp_path): + with pytest.raises(ValueError, match="single-particle"): + train_lan_for_model("race_3", tmp_path, estimator="pyddm") + assert not list(tmp_path.iterdir()) + + +def test_recipe_never_reuses_a_stale_output_certificate(tmp_path): + certificate = tmp_path / "model_config.json" + certificate.write_text("prior run") + with pytest.raises(FileExistsError, match="never reuse"): + train_lan_for_model("ddm", tmp_path) + assert certificate.read_text() == "prior run" + + def test_skipped_or_missing_gate_cannot_certify(tmp_path): passing = {g: {"passed": True} for g in ("G1", "G2", "G3", "G4", "G5")} artifact = LANArtifact(tmp_path / "net.onnx", {}, passing, {}, tmp_path) @@ -236,3 +273,66 @@ def test_toy_recipe_runs_real_runtime_angle_training_without_certificate(tmp_pat from lanfactory.recipes.validation import gate_structure assert gate_structure(artifact.onnx_path, len(cfg["params"]) + 2)["passed"] + + +@pytest.mark.slow +def test_real_hssm_validation_rejects_an_undertrained_nonanalytic_model(tmp_path): + pytest.importorskip("hssm") + cfg = ModelConfigBuilder.from_model("angle") + cfg["param_bounds"][0][0] = -0.5 + cfg["param_bounds"][1][0] = 0.5 + artifact = train_lan_for_model( + "angle", + tmp_path, + model_config=cfg, + fixed_parameters={"a": 1.0, "z": 0.5, "t": 0.2, "theta": 0.2}, + generator_config={ + "pipeline": {"n_parameter_sets": 4}, + "training": {"n_samples_per_param": 64}, + }, + network_config={"layer_sizes": [16, 1], "activations": ["tanh", "linear"]}, + train_config={"n_epochs": 1}, + ) + assert artifact.validation["G1"]["passed"] + assert artifact.validation["G2"]["passed"] + assert artifact.validation["G3"]["passed"], artifact.validation["G3"] + # This is an intentionally undertrained likelihood: good export and + # finite HSSM logp do not establish a usable density or its sensitivity. + assert not artifact.validation["G4"]["passed"] + assert len(artifact.validation["G5"]["points"]) == 5 + assert ( + max(p["autodiff_max_error"] for p in artifact.validation["G5"]["points"]) < 0.01 + ) + assert artifact.hssm_model_config is None + assert not (tmp_path / "model_config.json").exists() + + +@pytest.mark.parametrize("structure_passes", [True, False]) +def test_certificate_output_boundary_with_injected_gate_verdicts( + tmp_path, monkeypatch, structure_passes +): + from lanfactory.recipes import validation + + monkeypatch.setattr( + validation, "gate_structure", lambda *a: {"passed": structure_passes} + ) + # Isolate orchestration/output from the independently tested statistical + # gates. Training and export are real; this is not a likelihood-quality test. + for name in ("gate_hssm", "gate_density", "gate_gradient"): + monkeypatch.setattr(validation, name, lambda *a, **kw: {"passed": True}) + artifact = train_lan_for_model( + "angle", + tmp_path, + fixed_parameters={"a": 1.0, "z": 0.5, "t": 0.2, "theta": 0.2}, + generator_config={ + "pipeline": {"n_parameter_sets": 4}, + "training": {"n_samples_per_param": 64}, + }, + train_config={"n_epochs": 1}, + ) + assert artifact.validated is structure_passes + assert (tmp_path / "model_config.json").exists() is structure_passes + if structure_passes: + assert artifact.hssm_model_config["default_priors"]["theta"] == 0.2 + else: + assert all(artifact.validation[g]["skipped"] for g in ("G2", "G3", "G4", "G5")) From 634df09af7ac170d14fd887ad5e30e4b58a39624 Mon Sep 17 00:00:00 2001 From: Francesco Muia Date: Tue, 24 Nov 2026 13:59:30 +0100 Subject: [PATCH 5/5] Cover likelihood safety failures and artifact contracts --- tests/test_recipe_gradient.py | 17 +++++ tests/test_ssms_recipe.py | 119 ++++++++++++++++++++++++++++++++++ 2 files changed, 136 insertions(+) diff --git a/tests/test_recipe_gradient.py b/tests/test_recipe_gradient.py index 995288c..1bd2c5e 100644 --- a/tests/test_recipe_gradient.py +++ b/tests/test_recipe_gradient.py @@ -77,3 +77,20 @@ def test_export_parity_rejects_a_different_network(tmp_path): validation.ONNXPredictor(path), network, np.ones((5, 4)) ) assert gate["passed"] is False + + +def test_single_trial_gate_rejects_multiple_outputs(tmp_path): + class TwoOutputs(torch.nn.Module): + def __init__(self): + super().__init__() + self.layer = torch.nn.Linear(4, 1) + + def forward(self, x): + y = self.layer(x) + return y, y + 1 + + path = tmp_path / "two-outputs.onnx" + torch.onnx.export(TwoOutputs(), torch.zeros(1, 4), str(path), dynamo=False) + check = validation.gate_structure(path, 4) + assert check["passed"] is False + assert "one input and output" in check["error"] diff --git a/tests/test_ssms_recipe.py b/tests/test_ssms_recipe.py index 646a4b7..4f26fa1 100644 --- a/tests/test_ssms_recipe.py +++ b/tests/test_ssms_recipe.py @@ -92,6 +92,54 @@ def test_registered_bounds_are_normalized_without_mutation(monkeypatch): assert config == before +def test_named_bounds_without_legacy_rows_are_supported(): + cfg = ModelConfigBuilder.from_model("ddm") + expected = deepcopy(cfg["param_bounds_dict"]) + cfg.pop("param_bounds") + assert normalize_model_config(cfg)["param_bounds_dict"] == expected + + +@pytest.mark.parametrize( + "change,match", + [ + ({"params": []}, "nonempty and unique"), + ({"params": ["v", "v"]}, "nonempty and unique"), + ({"choices": [0]}, "distinct"), + ({"choices": [0, 0]}, "distinct"), + ( + {"param_bounds": [[-3.0, 0.3, 0.1, 0.0], [3.0, 3.0, 0.9, "t"]]}, + "numeric bounds", + ), + ], +) +def test_invalid_model_contracts_are_actionable(change, match): + with pytest.raises(ValueError, match=match): + normalize_model_config(ModelConfigBuilder.from_model("ddm") | change) + + +def test_unknown_fixed_parameter_is_not_silently_ignored(): + with pytest.raises(ValueError, match="unknown parameters"): + normalize_model_config(ModelConfigBuilder.from_model("ddm"), {"typo": 1.0}) + + +def test_invalid_boxes_abort_instead_of_retrying_indefinitely(): + guarded = pipeline() + for _ in range(100): + assert not guarded._is_valid_simulation(fixture_sim([20.1] * 6))[0] + with pytest.raises(RuntimeError, match="narrow the training box or extend max_t"): + guarded._is_valid_simulation(fixture_sim([20.1] * 6)) + + +def test_hssm_config_preserves_nondecision_support_declaration(): + cfg = { + "params": ["t", "st"], + "choices": [-1, 1], + "param_bounds_dict": {"t": [0.1, 1.0], "st": [0.0, 0.1]}, + "ndt_edge_shift": {"param": "st", "scale": 0.5}, + } + assert hssm_config(cfg)["ndt_edge_shift"] == cfg["ndt_edge_shift"] + + def test_bounds_from_raw_source_override_stale_derived_bounds(): cfg = ModelConfigBuilder.from_model("ddm") cfg["param_bounds"][0][0], cfg["param_bounds"][1][0] = -1.0, 1.0 @@ -238,6 +286,77 @@ def evaluate(self, rt, choice): assert "nonfinite reference" in check["error"] +@pytest.mark.parametrize("logp", [np.nan, 81.0]) +def test_nonfinite_or_exploding_network_cannot_pass_density(monkeypatch, logp): + from lanfactory.recipes import validation + + monkeypatch.setattr(validation, "simulate", lambda *a, **kw: fixture_sim()) + + class KDE: + def evaluate(self, rt, choice): + return np.full(len(rt), -np.log(40)) + + monkeypatch.setattr(validation, "make_kde", lambda x: KDE()) + check = gate_density( + lambda rows: np.full(len(rows), logp), + {"choices": [0, 1]}, + [np.array([1.0])], + n_sim=6, + seed=1, + max_t=20.0, + delta_t=0.001, + ) + assert check["passed"] is False + assert "network density" in check["error"] + + +def test_missing_hssm_cannot_pass_load_or_gradient(monkeypatch, tmp_path): + from lanfactory.recipes import validation + + find_spec = validation.importlib.util.find_spec + monkeypatch.setattr( + validation.importlib.util, + "find_spec", + lambda name: None if name == "hssm" else find_spec(name), + ) + path = tmp_path / "not-used.onnx" + checks = [ + validation.gate_hssm(path, {}, {}), + validation.gate_gradient( + path, None, {}, [], n_sim=1, seed=1, max_t=20.0, delta_t=0.001 + ), + ] + assert all(c["passed"] is False and c["skipped"] for c in checks) + + +@pytest.mark.parametrize( + "draws,match", + [ + (fixture_sim([20.1] * 6), "horizon"), + (fixture_sim(choices=[0] * 6), "missing a possible choice"), + ], +) +def test_fresh_validation_simulation_rejects_bad_observations( + monkeypatch, draws, match +): + import ssms + + from lanfactory.recipes import validation + + class Simulator: + def __init__(self, *args): + pass + + def simulate(self, *args, **kwargs): + return draws + + monkeypatch.setattr(ssms, "Simulator", Simulator) + with pytest.raises(ValueError, match=match): + validation.simulate( + {"params": ["v"], "choices": [0, 1]}, [1.0], 6, 1, 20.0, 0.001 + ) + + def test_nonfinite_failed_metrics_remain_strict_json(tmp_path): import json