"""Frozen configuration dataclasses and JSON (de)serialisation. The dataclasses mirror the GATE ZERO config contract (``E1_genus_information_ ceiling.md`` §5.1) with the E1-v2 deltas (fixed 11-taxa membership, no class-ladder machinery) and the binding deviations recorded in its §12: ``ModelConfig`` carries the realised fields ``d_model`` / ``n_layers`` / ``params_realised`` that ``build_probe`` fills in, and ``RunConfig`` records the realised genera so a run directory round-trips deterministically. """ from __future__ import annotations import json from dataclasses import dataclass, is_dataclass from pathlib import Path from typing import Any, Literal Arch = Literal["cnn", "linatt"] Stage = Literal["ladder_point", "windows_ablation", "robustness", "control", "extra"] AmpPolicy = Literal["off", "bf16", "fp16"] EarlyStopMetric = Literal["val_recall_macro", "val_loss"] NormMethod = Literal["median_iqr", "median_mad"] @dataclass(frozen=True) class DataConfig: """Split-time data selection and read-level split parameters.""" genera: tuple[str, ...] = () val_fraction: float = 0.10 test_fraction: float = 0.10 holdout_runs: bool = False min_test_windows_per_genus: int = 300 seed: int = 0 @dataclass(frozen=True) class ModelConfig: """Probe architecture request; realised geometry is filled by ``build_probe``. Attributes: arch: Encoder family, ``"cnn"`` or ``"linatt"``. param_budget: Nominal trainable-parameter budget in params (e.g. ``1_000_000``). Only the nominal budget enters the run id; the gate arithmetic always uses ``params_realised``. stride: Patch stride in signal samples, 4 or 8 (token pitch). d_embed: Pooled embedding width the encoder terminates in. budget_tol: Relative tolerance around the budget; the realised count must satisfy ``count_params <= (1 + budget_tol) * param_budget``. n_heads: Attention head count for the ``"linatt"`` arch (recorded so checkpoint rehydration rebuilds the exact geometry). d_model: realised token width (filled by ``build_probe``, ``None`` on a request config). n_layers: realised block count (filled by ``build_probe``). params_realised: realised trainable parameter count (filled by ``build_probe``; the only source of truth for reporting). """ arch: Arch param_budget: int stride: int d_embed: int = 256 budget_tol: float = 0.10 n_heads: int = 4 d_model: int | None = None n_layers: int | None = None params_realised: int | None = None @dataclass(frozen=True) class TrainConfig: """Training semantics (GATE ZERO §5.1; restated in the torch model spec §5).""" batch_size: int = 256 # Effective optimiser batch stays ``batch_size``; the loaders emit # micro-batches of ``batch_size // grad_accum`` and gradients are # accumulated over ``grad_accum`` of them before each step, so small # GPUs (16 GB) can honour the spec's batch 256. grad_accum: int = 1 lr: float = 3e-4 weight_decay: float = 0.01 max_epochs: int = 40 warmup_frac: float = 0.05 label_smoothing: float = 0.0 amp: AmpPolicy = "bf16" grad_clip: float = 1.0 early_stop_metric: EarlyStopMetric = "val_recall_macro" patience: int = 5 num_workers: int = 4 device: str | None = None seed: int = 0 deterministic: bool = True @dataclass(frozen=True) class ExtractConfig: """Pod5-to-store extraction parameters for ``extract_store``. Attributes: pod5_paths: Pod5 files to scan, processed in sorted path order. window_samples: Fixed window length in samples (12,000 ≈ 2.4 s at 5 kHz ≈ ~1 kb) — the model-input contract. skip_head_samples: Head samples skipped before the first window (adapter / mux artefacts). max_windows_per_read: Windows taken per read; 1 is the headline, 4 is the Stage-A' ablation row. Windows are contiguous from the first. min_read_samples: Reads shorter than this are dropped and counted in the store meta (must fit skip-head plus one full window). norm: Per-window normaliser applied before storing. dtype: On-disk shard dtype; fp16 halves the store at negligible cost. shard_windows: Windows per ``shard_%05d.npy`` file. exclude_refs: Reference contig substrings whose labelled reads are dropped (e.g. ``("NC_001416", "dcs")`` for ONT DNA Control Sequence spike-ins that would otherwise be mislabelled into Enterobacteriaceae genera). exclude_genera: Genus labels dropped before extraction (e.g. trap captures — reads of trap species that the labeller pulled into the panel but that belong to no class of the probe). seed: Unused by extraction itself (window choice is deterministic); kept so every config in the pipeline is seed-carrying. """ pod5_paths: tuple[Path, ...] window_samples: int = 12_000 skip_head_samples: int = 500 max_windows_per_read: int = 1 min_read_samples: int = 12_500 norm: NormMethod = "median_iqr" dtype: Literal["float16", "float32"] = "float16" shard_windows: int = 8_192 exclude_refs: tuple[str, ...] = () exclude_genera: tuple[str, ...] = () seed: int = 0 @dataclass(frozen=True) class RunConfig: """One experiment run: a store, data/model/train sub-configs and outputs. ``train_run`` fills ``run_id`` (if empty) and ``genera`` (from the realised splits) before the realised config is serialised into the run directory. """ run_id: str stage: Stage store_dir: Path data: DataConfig model: ModelConfig train: TrainConfig out_dir: Path genera: tuple[str, ...] = () notes: str = "" def run_id_for(arch: str, param_budget: int, stride: int, n_genera: int, stage: str) -> str: """Build the deterministic, filesystem-safe run identifier. Format: ``{arch}_{budget in M:.1f}M_s{stride}_g{n_genera}``, e.g. ``cnn_1.0M_s4_g11``; the control stage appends ``-shuf``. Only the nominal budget and class count enter the id — realised geometry never does — so ids are unique within the run matrix and stable across rehydration. Args: arch: Encoder family name (``"cnn"`` or ``"linatt"``). param_budget: Nominal parameter budget (divided by 1e6 for the tag). stride: Token stride in samples. n_genera: Number of selected classes (the ``g`` component). stage: Run stage; ``"control"`` triggers the ``-shuf`` suffix. Returns: The run id string. """ run_id = f"{arch}_{param_budget / 1_000_000:.1f}M_s{stride}_g{n_genera}" if stage == "control": return f"{run_id}-shuf" return run_id _TYPE_KEY = "__type__" _DATACLASSES: dict[str, type] = { cls.__name__: cls for cls in (DataConfig, ModelConfig, TrainConfig, ExtractConfig, RunConfig) } def _encode(obj: Any) -> Any: """Recursively convert a config object into a JSON-friendly payload. ``Path`` becomes ``{"__type__": "path", "value": str}``, tuples become tagged sequences (so they round-trip as tuples), and dataclass instances become dicts tagged with their class name. All other values pass through unchanged. Args: obj: A config dataclass, ``Path``, tuple/list, or plain JSON value. Returns: The JSON-serialisable encoding of ``obj``. """ if isinstance(obj, Path): return {_TYPE_KEY: "path", "value": str(obj)} if isinstance(obj, (tuple, list)): return {_TYPE_KEY: "seq", "value": [_encode(v) for v in obj]} if is_dataclass(obj) and not isinstance(obj, type): payload: dict[str, Any] = {_TYPE_KEY: type(obj).__name__} for field in obj.__dataclass_fields__: payload[field] = _encode(getattr(obj, field)) return payload return obj def _decode(obj: Any) -> Any: """Invert :func:`_encode` back into config objects. Tagged dicts rebuild ``Path`` values, tuples and registered dataclasses; anything else is returned as-is. Unknown ``__type__`` tags fall through as plain dicts so foreign JSON never crashes decoding. Args: obj: A payload produced by :func:`_encode` (or nested JSON value). Returns: The reconstructed config object. """ if isinstance(obj, dict): kind = obj.get(_TYPE_KEY) if kind == "path": return Path(obj["value"]) if kind == "seq": return tuple(_decode(v) for v in obj["value"]) if kind in _DATACLASSES: cls = _DATACLASSES[kind] kwargs = {} for name, field in cls.__dataclass_fields__.items(): if name in obj: kwargs[name] = _decode(obj[name]) elif field.default is not None: pass return cls(**kwargs) return obj def save_config(cfg: Any, path: Path) -> None: """Serialise a config dataclass to pretty JSON. Parent directories are created as needed. The payload uses the ``"__type__"`` discriminator scheme (GATE ZERO §12.7) so ``load_config(save_config(c)) == c`` holds exactly. Args: cfg: A config dataclass (or nested structure of them). path: Destination JSON file path. """ path = Path(path) path.parent.mkdir(parents=True, exist_ok=True) path.write_text(json.dumps(_encode(cfg), indent=2, sort_keys=True) + "\n") def load_config(path: Path) -> Any: """Load a config dataclass written by :func:`save_config`. Args: path: JSON config file path. Returns: The reconstructed config object (type depends on the file). Raises: FileNotFoundError: If ``path`` does not exist. ValueError: If the file is not valid JSON or does not decode into the recorded dataclass schema. """ path = Path(path) if not path.is_file(): raise FileNotFoundError(f"config file not found: {path}") try: return _decode(json.loads(path.read_text())) except (KeyError, TypeError, json.JSONDecodeError) as exc: raise ValueError(f"malformed config file: {path}: {exc}") from exc