From e648f480856017428d65e5124ec26cfadbb3f9c0 Mon Sep 17 00:00:00 2001 From: David Abbasi Perez Date: Tue, 7 Jul 2026 15:39:24 +0200 Subject: [PATCH 01/15] feat(labeling): per-frame failure isolation (on_error skip/raise), quarantined failures, and receipt-based resume that reuses completed frames and retries failed ones Co-Authored-By: Claude Fable 5 Claude-Session: https://claude.ai/code/session_01V6f4Z4uLdysBeehYfbQ56k --- docs/concepts/calculators.md | 13 ++- docs/reference/config.md | 11 ++ src/traincraft/config/models.py | 6 + src/traincraft/labeling.py | 146 +++++++++++++++++++++---- src/traincraft/orchestration/stages.py | 7 +- tests/test_labeling.py | 104 ++++++++++++++++++ 6 files changed, 262 insertions(+), 25 deletions(-) diff --git a/docs/concepts/calculators.md b/docs/concepts/calculators.md index 94f2bc0..2672e0d 100644 --- a/docs/concepts/calculators.md +++ b/docs/concepts/calculators.md @@ -117,13 +117,24 @@ This produces, under the run workspace: ``` labeled_dft/ labeled.extxyz # frames with E/F/stress(+dipole/pol) and origin=dft_labeled - manifest.json # level of theory, property set, frame count, wall time + manifest.json # level of theory, property set, counts (attempted/failed/reused), failures frame_0000/ … # per-frame work dirs (so file-IO calcs don't collide) + result.json # per-frame receipt: status + fingerprint (+ error on failure) + labeled.extxyz # the frame's own result (reused on rerun) ``` Each labeled frame is tagged `origin="dft_labeled"` with its `level_of_theory`, so the expensive data stays cleanly separable from the cheap, ML-generated points (see [Provenance](provenance.md)). The dataset is built from these labeled frames. +**Failures don't kill the batch.** SCF non-convergence and walltime kills are +routine at scale, so by default (`on_error = "skip"` in `[labeling]`) a failed +frame is quarantined — its input written to `frame_XXXX/input.extxyz`, the error +recorded in `manifest.json` — and labeling continues; set `on_error = "raise"` +to abort on the first failure instead. If every frame fails, the stage raises +regardless. **Reruns resume**: each frame's `result.json` receipt fingerprints +its geometry + level of theory, so completed frames are reused and only failed +(or changed) frames are recomputed. + > Tip: to *try the mechanics* with zero deps, set `[labeling.calculator] type = > "emt"` — EMT stands in for DFT and produces E/F/stress. `examples/18` does this. diff --git a/docs/reference/config.md b/docs/reference/config.md index fbb296e..a74964b 100644 --- a/docs/reference/config.md +++ b/docs/reference/config.md @@ -501,8 +501,12 @@ cheap `[calculator]` that drives sampling. Presence of this section enables the | Field | Type | Default | Description | |---|---|---|---| | `calculator` | calculator config | required | A `[labeling.calculator]` sub-table; usually `fhi_aims` or `qe` (any calculator works — `emt` stands in for DFT in demos) | +| `on_error` | `"skip" \| "raise"` | `"skip"` | What one failed frame does to the batch. `"skip"` quarantines the frame's input under its `frame_XXXX/` dir, records the error in `manifest.json`, and continues; `"raise"` aborts on the first failure. If **every** frame fails the stage raises regardless. | ```toml +[labeling] +on_error = "skip" # partial success is the normal outcome at scale + [labeling.calculator] type = "fhi_aims" xc = "pbe" @@ -510,6 +514,13 @@ species_defaults = "tight" properties = ["polarizability"] # E/F/stress always; + dipole/polarizability on request ``` +Each frame runs in its own `frame_XXXX/` work dir and writes a `result.json` +receipt (status + a fingerprint of the frame geometry and level of theory) plus +`labeled.extxyz` on success. **Reruns resume**: frames whose receipt matches are +reused without recomputation, failed frames are retried, and `manifest.json` +reports `n_attempted` / `n_frames` / `n_failed` / `n_reused` with per-frame +error messages. + See [Calculators & DFT Labeling](../concepts/calculators.md) for the DFT calculator fields and the environment-injected run command. diff --git a/src/traincraft/config/models.py b/src/traincraft/config/models.py index 1142b98..2867905 100644 --- a/src/traincraft/config/models.py +++ b/src/traincraft/config/models.py @@ -736,9 +736,15 @@ class LabelingConfig(TCModel): Use a DFT calculator (`fhi_aims`/`qe`) here to label the funnel's output with energy/forces/stress (+ dipole/polarizability); the cheap `[calculator]` used for sampling is configured separately. + + ``on_error`` decides what one failed frame does to the batch: ``"skip"`` + (default) quarantines it, records the error in the manifest and continues — + at scale partial success is the normal outcome — while ``"raise"`` aborts on + the first failure. If *every* frame fails the stage raises regardless. """ calculator: CalculatorConfig + on_error: Literal["skip", "raise"] = "skip" # --------------------------------------------------------------------------- dataset diff --git a/src/traincraft/labeling.py b/src/traincraft/labeling.py index 5ae1a19..0273246 100644 --- a/src/traincraft/labeling.py +++ b/src/traincraft/labeling.py @@ -6,12 +6,24 @@ level of theory, so the costly data stays cleanly separable from the cheap, ML-generated points. +At scale, partial success is the *normal* outcome: SCF non-convergence, walltime +kills and bad initial guesses are routine. So failures are isolated per frame — +``on_error="skip"`` (the default) quarantines the failed frame's input, records +the error in the manifest, and keeps going; ``"raise"`` aborts on first failure. +If every frame fails, the stage raises regardless (an empty artifact would only +hide a broken setup). + Each frame is computed in its own sub-directory (``frame_0000/`` …) so file-IO -calculators (FHI-aims, QE) don't clobber one another and reruns are resumable. +calculators (FHI-aims, QE) don't clobber one another, and each writes a +``result.json`` receipt plus its ``labeled.extxyz`` on success. A rerun reuses +completed frames whose receipt matches the current frame + level of theory, and +retries failed ones — so a crashed or partially failed labeling run resumes +instead of recomputing everything. """ from __future__ import annotations +import hashlib import json import logging import time @@ -21,6 +33,7 @@ from .calculators import make_calculator from .core import Structure +from .datasets.io import read_frames, write_frames logger = logging.getLogger(__name__) @@ -30,42 +43,108 @@ def _level_of_theory(calc_cfg) -> dict: return {"calculator": data.pop("type"), **data} -def label_frames(frames: list[Structure], calc_cfg, *, out_dir=None) -> list[Structure]: +def _fingerprint(s: Structure, level: dict, extra_props: list[str]) -> str: + """What a frame's label depends on: its geometry and the level of theory.""" + blob = json.dumps( + {"hash": s.hash, "level": level, "props": sorted(extra_props)}, + sort_keys=True, + default=str, + ).encode() + return hashlib.sha256(blob).hexdigest()[:16] + + +def _write_result(frame_dir: Path, record: dict) -> None: + (frame_dir / "result.json").write_text(json.dumps(record, indent=2)) + + +def _reuse(frame_dir: Path, fingerprint: str) -> Structure | None: + """The frame's previous result, if it succeeded under the same fingerprint.""" + result_file = frame_dir / "result.json" + labeled_file = frame_dir / "labeled.extxyz" + if not (result_file.exists() and labeled_file.exists()): + return None + try: + record = json.loads(result_file.read_text()) + except json.JSONDecodeError: + return None + if record.get("status") != "ok" or record.get("fingerprint") != fingerprint: + return None + frames = read_frames(labeled_file) + return frames[0] if frames else None + + +def _compute(atoms, calc, calc_cfg, extra_props: list[str]) -> dict: + atoms.calc = calc + props: dict = { + "energy": float(atoms.get_potential_energy()), + "forces": np.asarray(atoms.get_forces()), + } + if atoms.cell.rank == 3 and atoms.get_pbc().any(): + try: + props["stress"] = np.asarray(atoms.get_stress()) + except Exception: # calc/system may not support stress + logger.debug("calculator %s produced no stress", calc_cfg.type) + if "dipole" in extra_props: + props["dipole"] = np.asarray(atoms.get_dipole_moment()) + if "polarizability" in extra_props: + pol = getattr(calc, "results", {}).get("polarizability") + if pol is not None: + props["polarizability"] = np.asarray(pol) + return props + + +def label_frames( + frames: list[Structure], calc_cfg, *, out_dir=None, on_error: str = "skip" +) -> list[Structure]: """Label ``frames`` with ``calc_cfg``; return new ``dft_labeled`` Structures. - ``out_dir`` (a directory) enables per-frame work dirs and writes a - ``manifest.json`` recording the level of theory and the property set. + ``out_dir`` (a directory) enables per-frame work dirs, per-frame resume, and + a ``manifest.json`` recording the level of theory, the property set, and any + failures. ``on_error="skip"`` drops failed frames (quarantining their input + for inspection); ``"raise"`` propagates the first failure. """ + if on_error not in ("skip", "raise"): + raise ValueError(f"on_error must be 'skip' or 'raise', not {on_error!r}") calc = make_calculator(calc_cfg) extra_props = list(getattr(calc_cfg, "properties", []) or []) level = _level_of_theory(calc_cfg) out_dir = Path(out_dir) if out_dir is not None else None labeled: list[Structure] = [] + failures: list[dict] = [] + n_reused = 0 t0 = time.perf_counter() for i, s in enumerate(frames): - atoms = s.to_ase(with_properties=False) - if out_dir is not None and hasattr(calc, "directory"): + fingerprint = _fingerprint(s, level, extra_props) + frame_dir = None + if out_dir is not None: frame_dir = out_dir / f"frame_{i:04d}" + previous = _reuse(frame_dir, fingerprint) + if previous is not None: + labeled.append(previous) + n_reused += 1 + logger.info("labeled %d/%d (reused previous result)", i + 1, len(frames)) + continue frame_dir.mkdir(parents=True, exist_ok=True) - calc.directory = str(frame_dir) - atoms.calc = calc + if hasattr(calc, "directory"): + calc.directory = str(frame_dir) - props: dict = { - "energy": float(atoms.get_potential_energy()), - "forces": np.asarray(atoms.get_forces()), - } - if atoms.cell.rank == 3 and atoms.get_pbc().any(): - try: - props["stress"] = np.asarray(atoms.get_stress()) - except Exception: # calc/system may not support stress - logger.debug("calculator %s produced no stress", calc_cfg.type) - if "dipole" in extra_props: - props["dipole"] = np.asarray(atoms.get_dipole_moment()) - if "polarizability" in extra_props: - pol = getattr(calc, "results", {}).get("polarizability") - if pol is not None: - props["polarizability"] = np.asarray(pol) + atoms = s.to_ase(with_properties=False) + t_frame = time.perf_counter() + try: + props = _compute(atoms, calc, calc_cfg, extra_props) + except Exception as exc: + if on_error == "raise": + raise + error = f"{type(exc).__name__}: {exc}" + failures.append({"frame": i, "error": error}) + logger.warning("frame %d/%d failed, skipping: %s", i + 1, len(frames), error) + if frame_dir is not None: + write_frames(frame_dir / "input.extxyz", [s]) + _write_result( + frame_dir, {"status": "failed", "fingerprint": fingerprint, "error": error} + ) + continue new = s.copy() new.properties = props @@ -73,14 +152,35 @@ def label_frames(frames: list[Structure], calc_cfg, *, out_dir=None) -> list[Str new.provenance.calculator = calc_cfg.type new.provenance.level_of_theory = level labeled.append(new) + if frame_dir is not None: + write_frames(frame_dir / "labeled.extxyz", [new]) + _write_result( + frame_dir, + { + "status": "ok", + "fingerprint": fingerprint, + "wall_seconds": round(time.perf_counter() - t_frame, 2), + }, + ) logger.info("labeled %d/%d (E = %.4f eV)", i + 1, len(frames), props["energy"]) + if frames and not labeled: + raise RuntimeError( + f"labeling failed for all {len(frames)} frames " + f"(first error: {failures[0]['error']})" + ) + if out_dir is not None: manifest = { "level_of_theory": level, "calculator": calc_cfg.type, "properties": ["energy", "forces", "stress", *extra_props], "n_frames": len(labeled), + "n_attempted": len(frames), + "n_failed": len(failures), + "n_reused": n_reused, + "failures": failures, + "on_error": on_error, "wall_seconds": round(time.perf_counter() - t0, 2), "origin": "dft_labeled", } diff --git a/src/traincraft/orchestration/stages.py b/src/traincraft/orchestration/stages.py index bc17c40..e165cb7 100644 --- a/src/traincraft/orchestration/stages.py +++ b/src/traincraft/orchestration/stages.py @@ -223,7 +223,12 @@ def stage_label(config, ws, force=False): return read_frames(out) job = ws.job("labeled_dft") frames = _latest_upstream(ws, "label") - labeled = label_frames(frames, config.labeling.calculator, out_dir=job.dir) + labeled = label_frames( + frames, + config.labeling.calculator, + out_dir=job.dir, + on_error=config.labeling.on_error, + ) write_frames(out, labeled) _write_key(out, key) return labeled diff --git a/tests/test_labeling.py b/tests/test_labeling.py index 97a0355..27a8cca 100644 --- a/tests/test_labeling.py +++ b/tests/test_labeling.py @@ -2,6 +2,10 @@ import json +import pytest +from ase.calculators.calculator import all_changes +from ase.calculators.emt import EMT + from traincraft import label_frames, read_frames, run_pipeline from traincraft.config.models import ( CrystalBuilder, @@ -54,6 +58,106 @@ def test_label_frames_writes_manifest_and_frame_dirs(tmp_path): assert (tmp_path / "frame_0000").is_dir() +class _FlakyEMT(EMT): + """EMT that raises on chosen compute attempts — a stand-in for SCF failures.""" + + def __init__(self, fail_on=(), **kwargs): + super().__init__(**kwargs) + self.n_compute = 0 + self._fail_on = set(fail_on) + + def calculate(self, atoms=None, properties=("energy",), system_changes=all_changes): + attempt = self.n_compute + self.n_compute += 1 + if attempt in self._fail_on: + raise RuntimeError("SCF did not converge (simulated)") + super().calculate(atoms, properties, system_changes) + + +def _patch_calc(monkeypatch, calc): + monkeypatch.setattr("traincraft.labeling.make_calculator", lambda cfg: calc) + return calc + + +def test_label_frames_skips_and_quarantines_failed_frames(tmp_path, monkeypatch): + _patch_calc(monkeypatch, _FlakyEMT(fail_on={1})) + labeled = label_frames(_cu_frames(3), EmtCalc(), out_dir=tmp_path) + assert len(labeled) == 2 + + manifest = json.loads((tmp_path / "manifest.json").read_text()) + assert manifest["n_attempted"] == 3 + assert manifest["n_frames"] == 2 + assert manifest["n_failed"] == 1 + assert manifest["failures"][0]["frame"] == 1 + assert "SCF did not converge" in manifest["failures"][0]["error"] + + failed_dir = tmp_path / "frame_0001" + result = json.loads((failed_dir / "result.json").read_text()) + assert result["status"] == "failed" + assert (failed_dir / "input.extxyz").exists() # quarantined for inspection + assert not (failed_dir / "labeled.extxyz").exists() + + +def test_label_frames_on_error_raise_propagates(monkeypatch): + _patch_calc(monkeypatch, _FlakyEMT(fail_on={1})) + with pytest.raises(RuntimeError, match="SCF did not converge"): + label_frames(_cu_frames(3), EmtCalc(), on_error="raise") + + +def test_label_frames_all_failed_raises_even_with_skip(monkeypatch): + _patch_calc(monkeypatch, _FlakyEMT(fail_on={0, 1, 2})) + with pytest.raises(RuntimeError, match="all 3 frames"): + label_frames(_cu_frames(3), EmtCalc(), on_error="skip") + + +def test_label_frames_rerun_reuses_completed_frames(tmp_path, monkeypatch): + frames = _cu_frames(2) + label_frames(frames, EmtCalc(), out_dir=tmp_path) + + # Rerun with a calculator that would fail everything: reuse means no compute. + flaky = _patch_calc(monkeypatch, _FlakyEMT(fail_on={0, 1, 2, 3})) + labeled = label_frames(frames, EmtCalc(), out_dir=tmp_path) + assert flaky.n_compute == 0 + assert len(labeled) == 2 + manifest = json.loads((tmp_path / "manifest.json").read_text()) + assert manifest["n_reused"] == 2 + assert all("energy" in s.properties for s in labeled) + assert all(s.provenance.origin == "dft_labeled" for s in labeled) + + +def test_label_frames_rerun_retries_failed_frames(tmp_path, monkeypatch): + frames = _cu_frames(3) + _patch_calc(monkeypatch, _FlakyEMT(fail_on={1})) + assert len(label_frames(frames, EmtCalc(), out_dir=tmp_path)) == 2 + + good = _FlakyEMT() # counts computes, never fails + _patch_calc(monkeypatch, good) + labeled = label_frames(frames, EmtCalc(), out_dir=tmp_path) + assert len(labeled) == 3 + assert good.n_compute == 1 # only the previously failed frame was recomputed + manifest = json.loads((tmp_path / "manifest.json").read_text()) + assert manifest["n_reused"] == 2 + assert manifest["n_failed"] == 0 + + +def test_label_frames_stale_fingerprint_recomputes(tmp_path, monkeypatch): + frames = _cu_frames(2) + label_frames(frames, EmtCalc(), out_dir=tmp_path) + + # A receipt from a different geometry/level of theory must not be reused. + result_file = tmp_path / "frame_0000" / "result.json" + record = json.loads(result_file.read_text()) + record["fingerprint"] = "0" * 16 + result_file.write_text(json.dumps(record)) + + counting = _patch_calc(monkeypatch, _FlakyEMT()) + labeled = label_frames(frames, EmtCalc(), out_dir=tmp_path) + assert len(labeled) == 2 + assert counting.n_compute == 1 + manifest = json.loads((tmp_path / "manifest.json").read_text()) + assert manifest["n_reused"] == 1 + + def test_pipeline_labels_selected_frames(tmp_path): cfg = TrainCraftConfig( run=RunConfig(name="lbl", outdir=str(tmp_path), seed=1), From cf1c881706c7f89fcd91c6851483befae0b6ccc3 Mon Sep 17 00:00:00 2001 From: David Abbasi Perez Date: Tue, 7 Jul 2026 17:26:36 +0200 Subject: [PATCH 02/15] feat(validation): parity metrics + thresholded quality_report.json as a 'validate' stage (defaults to the trained model and its holdout valid.xyz); decode array properties in read_frames Co-Authored-By: Claude Fable 5 Claude-Session: https://claude.ai/code/session_01V6f4Z4uLdysBeehYfbQ56k --- ROADMAP.md | 27 ++- docs/reference/config.md | 34 ++++ src/traincraft/__init__.py | 3 + src/traincraft/cli.py | 2 +- src/traincraft/config/models.py | 23 +++ src/traincraft/datasets/io.py | 13 +- src/traincraft/orchestration/local.py | 11 +- src/traincraft/orchestration/slurm.py | 3 +- src/traincraft/orchestration/stages.py | 46 ++++- src/traincraft/validation/__init__.py | 19 ++ src/traincraft/validation/metrics.py | 64 ++++++ src/traincraft/validation/validate.py | 267 +++++++++++++++++++++++++ tests/test_validation.py | 201 +++++++++++++++++++ 13 files changed, 700 insertions(+), 13 deletions(-) create mode 100644 src/traincraft/validation/__init__.py create mode 100644 src/traincraft/validation/metrics.py create mode 100644 src/traincraft/validation/validate.py create mode 100644 tests/test_validation.py diff --git a/ROADMAP.md b/ROADMAP.md index baa22c2..c55a067 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -216,15 +216,28 @@ Acceptance (met) Composition/space/volume coverage maps; energy and per-element force distributions with outlier flags; extrapolation grade; redundancy report. -### 🔜 Chunk 3 — Validation (`validation/`) - -Per-property parity + RMSE/MAE (per element), learning curves, NVE/MD stability, -EOS/phonons, **IR and Raman spectra reconstruction** from MLIP-driven MD vs -DFT/experiment. +### 🚧 Chunk 3 — Validation (`validation/`) *(parity + quality report done)* + +- ✅ `validation/` — parity metrics (RMSE/MAE for E [total + per-atom], forces + [overall + per-element], stress/dipole/polarizability) against reference + labels, with configurable **thresholds → pass/fail**, written as a data-first + `validation/quality_report.json` (metrics + checks + per-frame energy parity). + One artifact, three consumers: the researcher, a future dashboard, and the AL + loop's convergence criterion. +- ✅ `validate` stage (`[validation]`): model under test defaults to the one + `train` produced (`model/manifest.json`); reference frames default to the + training holdout `model/valid.xyz` (never trained on), overridable via + `test_file`. Slurm executor maps it to `traincraft-mlip.sif`. Failed frames + skip-and-record (same philosophy as labeling). +- 🔜 Learning curves (error vs dataset size), NVE/MD stability, EOS/phonons. +- 🔜 **IR and Raman spectra reconstruction** from MLIP-driven MD vs + DFT/experiment. Acceptance -- A fine-tuned model trains on a seed set and produces a quality report covering - every property, including reconstructed IR/Raman spectra. +- ✅ A model is validated per property with recorded pass/fail vs thresholds + (covered by `test_validation`, EMT standing in for the MLIP). +- 🔜 A fine-tuned model trains on a seed set and produces a quality report + covering every property, including reconstructed IR/Raman spectra. --- diff --git a/docs/reference/config.md b/docs/reference/config.md index a74964b..fde988e 100644 --- a/docs/reference/config.md +++ b/docs/reference/config.md @@ -583,3 +583,37 @@ scheduler = "ReduceLROnPlateau" `EnergyDipolesMACE`/`AtomicDipolesMACE`, `polarizability` → `AtomicDielectricMACE`. Override `--model`/`--loss`/keys via `[training.extra]` if your MACE version differs. + +--- + +## `[validation]` + +Measures a model against reference-labeled frames and writes +`validation/quality_report.json` — per-property parity metrics (RMSE/MAE, +per-element force errors), optional pass/fail thresholds, and per-frame energy +parity data. Presence of this section enables the `validate` stage (after +`train`). The same report is what a human reads, what a dashboard plots, and +what the future active-learning loop will use as its convergence criterion. + +| Field | Type | Default | Description | +|---|---|---|---| +| `calculator` | calculator config \| null | `null` | The model under test. Default: the model the `train` stage produced (from `model/manifest.json`), loaded as a `mace` calculator | +| `test_file` | path \| null | `null` | Explicit reference set (`tc_*` or training `REF_*` extxyz). Default: the training holdout `model/valid.xyz` (never seen in training), else the latest labeled/dataset artifact — beware that last fallback overlaps the training set | +| `properties` | list \| null | `null` | Which properties to check (`energy`/`forces`/`stress`/`dipole`/`polarizability`). Default: everything the reference frames carry | +| `max_frames` | `int \| null` | `null` | Cap the number of frames compared (quick checks) | +| `thresholds` | `dict` | `{}` | Metric name → maximum allowed value; the report records each check and an overall `passed`. Unknown metric names fail fast | + +Metric names for `thresholds`: `energy_rmse`, `energy_mae`, +`energy_rmse_per_atom`, `energy_mae_per_atom` (eV, eV/atom), `forces_rmse`, +`forces_mae` (eV/Å), and `_rmse`/`_mae` for +`stress`/`dipole`/`polarizability` when present. + +```toml +[validation] +# calculator omitted → validates the model just trained by [training] +thresholds = { forces_rmse = 0.05, energy_mae_per_atom = 0.005 } +``` + +A frame whose energy/forces prediction fails is skipped and recorded (same +philosophy as `[labeling]`'s `on_error="skip"`); optional properties the model +cannot produce are dropped per property without voiding the frame. diff --git a/src/traincraft/__init__.py b/src/traincraft/__init__.py index df75a73..6a33e3e 100644 --- a/src/traincraft/__init__.py +++ b/src/traincraft/__init__.py @@ -26,6 +26,7 @@ from .sampling import run_sampling from .selection import run_funnel from .training import run_training +from .validation import ValidationResult, run_validation __version__ = "0.1.0" @@ -35,6 +36,7 @@ "Result", "Structure", "TrainCraftConfig", + "ValidationResult", "Workspace", "available", "build_geometry", @@ -50,5 +52,6 @@ "run_pipeline", "run_sampling", "run_training", + "run_validation", "write_frames", ] diff --git a/src/traincraft/cli.py b/src/traincraft/cli.py index 86fdddd..a8e43e0 100644 --- a/src/traincraft/cli.py +++ b/src/traincraft/cli.py @@ -96,7 +96,7 @@ def validate(config: Path = typer.Argument(..., exists=True, readable=True)) -> name for name in ( "geometry", "calculator", "sampling", "selection", - "labeling", "dataset", "training", + "labeling", "dataset", "training", "validation", ) if getattr(cfg, name) is not None ] diff --git a/src/traincraft/config/models.py b/src/traincraft/config/models.py index 2867905..d035460 100644 --- a/src/traincraft/config/models.py +++ b/src/traincraft/config/models.py @@ -855,6 +855,28 @@ def _check(self) -> MaceTrainer: TrainingConfig = Annotated[MaceTrainer, Field(discriminator="type")] +# ------------------------------------------------------------------------ validation +class ValidationConfig(TCModel): + """Measure a model against reference-labeled frames → ``quality_report.json``. + + The model under test defaults to the one the ``train`` stage produced (from + ``model/manifest.json``); set ``calculator`` to validate any other model. + Reference frames come from, in order: ``test_file`` if set, the training + holdout ``model/valid.xyz`` (never seen in training), else the latest + labeled/dataset artifact — beware the last one overlaps the training set. + + ``thresholds`` maps metric names (e.g. ``forces_rmse``, + ``energy_mae_per_atom``) to maximum allowed values; the report records each + check and an overall ``passed``. Unknown metric names fail fast. + """ + + calculator: CalculatorConfig | None = None # default: the trained model + test_file: FsPath | None = None # explicit reference set (tc_* or REF_* extxyz) + properties: list[_HEAD] | None = None # default: whatever the references carry + max_frames: int | None = None # cap for quick checks + thresholds: dict[str, float] = Field(default_factory=dict) + + # --------------------------------------------------------------------- orchestration class SlurmStage(TCModel): """Per-stage Slurm/Apptainer overrides (merged onto built-in defaults).""" @@ -927,4 +949,5 @@ class TrainCraftConfig(TCModel): labeling: LabelingConfig | None = None dataset: DatasetConfig | None = None training: TrainingConfig | None = None + validation: ValidationConfig | None = None orchestration: OrchestrationConfig | None = None diff --git a/src/traincraft/datasets/io.py b/src/traincraft/datasets/io.py index f1c62df..99a5ed6 100644 --- a/src/traincraft/datasets/io.py +++ b/src/traincraft/datasets/io.py @@ -34,6 +34,17 @@ def _to_atoms(s: Structure): return atoms +def _decode(value): + """Undo the JSON-string encoding of array properties (see ``_to_atoms``), + so stress/dipole/polarizability round-trip as arrays, not strings.""" + if isinstance(value, str) and value.lstrip().startswith("["): + try: + return np.asarray(json.loads(value), dtype=float) + except (json.JSONDecodeError, ValueError): + return value + return value + + def write_frames(path: str | Path, structures: list[Structure], append: bool = False) -> Path: path = Path(path) path.parent.mkdir(parents=True, exist_ok=True) @@ -53,7 +64,7 @@ def read_frames(path: str | Path) -> list[Structure]: props["forces"] = np.asarray(atoms.arrays["tc_forces"]) for key in list(atoms.info): if key.startswith("tc_") and key not in _META_KEYS: - props[key[3:]] = atoms.info[key] + props[key[3:]] = _decode(atoms.info[key]) raw = atoms.info.get("tc_provenance") prov = Provenance.from_dict(json.loads(raw)) if raw else Provenance() out.append(Structure(atoms=atoms, properties=props, provenance=prov)) diff --git a/src/traincraft/orchestration/local.py b/src/traincraft/orchestration/local.py index 5ac05b4..f8538b5 100644 --- a/src/traincraft/orchestration/local.py +++ b/src/traincraft/orchestration/local.py @@ -7,12 +7,14 @@ from __future__ import annotations +import json import logging import numpy as np from ..config import TrainCraftConfig from ..datasets import Dataset +from ..validation import REPORT_NAME from .stages import ( stage_dataset, stage_geometry, @@ -20,6 +22,7 @@ stage_sample, stage_select, stage_train, + stage_validate, workspace_for, ) @@ -40,13 +43,14 @@ def run_pipeline(config: TrainCraftConfig, *, force: bool = False) -> dict: labeled = stage_label(config, ws, force=force) stage_dataset(config, ws, force=force) stage_train(config, ws, force=force) + stage_validate(config, ws, force=force) dataset_path = None if config.dataset is not None: dataset_path = str(Dataset(ws.root / config.dataset.path).path) model_dir = str(ws.root / "model") if config.training is not None else None - return { + summary = { "workspace": str(ws.root), "n_candidates": len(candidates), "n_selected": len(selected), @@ -54,3 +58,8 @@ def run_pipeline(config: TrainCraftConfig, *, force: bool = False) -> dict: "dataset": dataset_path, "model": model_dir, } + if config.validation is not None: + report_path = ws.root / "validation" / REPORT_NAME + summary["quality_report"] = str(report_path) + summary["validation_passed"] = json.loads(report_path.read_text())["passed"] + return summary diff --git a/src/traincraft/orchestration/slurm.py b/src/traincraft/orchestration/slurm.py index 27eb492..0b9f62a 100644 --- a/src/traincraft/orchestration/slurm.py +++ b/src/traincraft/orchestration/slurm.py @@ -52,8 +52,9 @@ "label": "traincraft-core.sif", "dataset": "traincraft-core.sif", "train": "traincraft-mlip.sif", + "validate": "traincraft-mlip.sif", # inference against the trained model } -_DEFAULT_GPUS = {"sample": 1, "train": 1} +_DEFAULT_GPUS = {"sample": 1, "train": 1, "validate": 1} _JOB_ID_RE = re.compile(r"Submitted batch job (\d+)") diff --git a/src/traincraft/orchestration/stages.py b/src/traincraft/orchestration/stages.py index e165cb7..02d4e1d 100644 --- a/src/traincraft/orchestration/stages.py +++ b/src/traincraft/orchestration/stages.py @@ -43,12 +43,14 @@ from ..sampling import run_sampling from ..selection import run_funnel from ..training import run_training +from ..validation import REPORT_NAME, load_reference_frames, resolve_calculator, run_validation logger = logging.getLogger(__name__) # Stages in pipeline order. dataset is terminal for frames; train consumes the -# dataset (or labelled frames) and emits a model rather than a frames artifact. -STAGE_ORDER = ("geometry", "sample", "select", "label", "dataset", "train") +# dataset (or labelled frames) and emits a model; validate consumes the model + +# reference frames and emits a quality report. +STAGE_ORDER = ("geometry", "sample", "select", "label", "dataset", "train", "validate") _PRODUCERS = ("geometry", "sample", "select", "label") _ARTIFACT = { "geometry": ("structures", "initial.extxyz"), @@ -71,6 +73,7 @@ def enabled_stages(config: TrainCraftConfig) -> list[str]: ("label", config.labeling), ("dataset", config.dataset), ("train", config.training), + ("validate", config.validation), ): if section is not None: stages.append(name) @@ -128,6 +131,7 @@ def _stage_inputs(config, stage: str) -> dict: "label": {"labeling": _dump(config.labeling)}, "dataset": {"dataset": _dump(config.dataset)}, "train": {"training": _dump(config.training)}, + "validate": {"validation": _dump(config.validation)}, }[stage] @@ -148,6 +152,13 @@ def _upstream_key(config, ws: Workspace, stage: str) -> str | None: """Key of the artifact this stage consumes (None if it has no producer yet).""" if stage == "train" and config.dataset is not None: return _read_key(Dataset(ws.root / config.dataset.path).path) + if stage == "validate": + # The report depends on the model under test: the train stage's manifest + # when one ran, else the frames artifact the fallback comparison uses. + if config.training is not None: + return _read_key(ws.root / "model" / "manifest.json") + if config.dataset is not None: + return _read_key(Dataset(ws.root / config.dataset.path).path) path = _latest_upstream_path(ws, stage) return _read_key(path) if path is not None else None @@ -278,6 +289,36 @@ def _training_frames(config, ws) -> list: return _latest_upstream(ws, "train") +def stage_validate(config, ws, force=False): + if config.validation is None: + return _latest_upstream(ws, "validate") + out = ws.root / "validation" / REPORT_NAME + key = _stage_key(config, ws, "validate") + if not force and _fresh(out, key): + logger.info("validate: up to date, skipping (%s)", out) + return _validation_frames(config, ws) + frames = _validation_frames(config, ws) + calc_cfg = resolve_calculator(config.validation, ws.root / "model" / "manifest.json") + result = run_validation(frames, calc_cfg, config.validation, out_dir=ws.root / "validation") + _write_key(out, key) + verdict = {True: "passed", False: "FAILED", None: "no thresholds set"}[result.passed] + logger.info( + "validated %d frames (%s): %s", result.n_frames, verdict, result.report_path + ) + return frames + + +def _validation_frames(config, ws) -> list: + """Reference frames: test_file > training holdout (valid.xyz) > upstream.""" + v = config.validation + if v.test_file: + return load_reference_frames(v.test_file) + valid_xyz = ws.root / "model" / "valid.xyz" + if config.training is not None and valid_xyz.exists(): + return load_reference_frames(valid_xyz) + return _training_frames(config, ws) + + _DISPATCH = { "geometry": stage_geometry, "sample": stage_sample, @@ -285,6 +326,7 @@ def _training_frames(config, ws) -> list: "label": stage_label, "dataset": stage_dataset, "train": stage_train, + "validate": stage_validate, } diff --git a/src/traincraft/validation/__init__.py b/src/traincraft/validation/__init__.py new file mode 100644 index 0000000..0808e59 --- /dev/null +++ b/src/traincraft/validation/__init__.py @@ -0,0 +1,19 @@ +"""Validation: parity metrics + quality report for a trained model.""" + +from __future__ import annotations + +from .validate import ( + REPORT_NAME, + ValidationResult, + load_reference_frames, + resolve_calculator, + run_validation, +) + +__all__ = [ + "REPORT_NAME", + "ValidationResult", + "load_reference_frames", + "resolve_calculator", + "run_validation", +] diff --git a/src/traincraft/validation/metrics.py b/src/traincraft/validation/metrics.py new file mode 100644 index 0000000..599ba50 --- /dev/null +++ b/src/traincraft/validation/metrics.py @@ -0,0 +1,64 @@ +"""Parity metrics: model predictions against reference labels (pure numpy). + +Each function takes aligned reference/prediction collections and returns a flat +``{metric_name: float}`` dict (plus one nested per-element dict for forces). +The names are the contract: thresholds in ``[validation]`` and the quality +report refer to metrics by exactly these keys. +""" + +from __future__ import annotations + +import numpy as np + + +def _rmse(diff: np.ndarray) -> float: + return float(np.sqrt(np.mean(np.square(diff)))) + + +def _mae(diff: np.ndarray) -> float: + return float(np.mean(np.abs(diff))) + + +def energy_metrics(ref: list[float], pred: list[float], n_atoms: list[int]) -> dict: + """Total (eV) and size-intensive per-atom (eV/atom) energy errors.""" + diff = np.asarray(pred, dtype=float) - np.asarray(ref, dtype=float) + per_atom = diff / np.asarray(n_atoms, dtype=float) + return { + "energy_rmse": _rmse(diff), + "energy_mae": _mae(diff), + "energy_rmse_per_atom": _rmse(per_atom), + "energy_mae_per_atom": _mae(per_atom), + } + + +def force_metrics( + ref: list[np.ndarray], pred: list[np.ndarray], symbols: list[list[str]] +) -> dict: + """Component-wise force errors (eV/Å), overall and grouped by element.""" + diffs = [ + np.asarray(p, dtype=float) - np.asarray(r, dtype=float) + for r, p in zip(ref, pred, strict=True) + ] + all_components = np.concatenate([d.ravel() for d in diffs]) + by_element: dict[str, list[np.ndarray]] = {} + for d, syms in zip(diffs, symbols, strict=True): + for row, symbol in zip(d, syms, strict=True): + by_element.setdefault(symbol, []).append(row) + return { + "forces_rmse": _rmse(all_components), + "forces_mae": _mae(all_components), + "forces_rmse_by_element": { + el: _rmse(np.asarray(rows).ravel()) for el, rows in sorted(by_element.items()) + }, + } + + +def array_metrics(name: str, ref: list[np.ndarray], pred: list[np.ndarray]) -> dict: + """Flattened component-wise errors for a tensor property (stress/dipole/…).""" + diff = np.concatenate( + [ + np.asarray(p, dtype=float).ravel() - np.asarray(r, dtype=float).ravel() + for r, p in zip(ref, pred, strict=True) + ] + ) + return {f"{name}_rmse": _rmse(diff), f"{name}_mae": _mae(diff)} diff --git a/src/traincraft/validation/validate.py b/src/traincraft/validation/validate.py new file mode 100644 index 0000000..c9b66e0 --- /dev/null +++ b/src/traincraft/validation/validate.py @@ -0,0 +1,267 @@ +"""Validation stage: measure a trained model against reference-labeled frames. + +This is the trust anchor of the pipeline. It produces a **data-first** +``quality_report.json``: per-property parity metrics (RMSE/MAE, per-element +force errors), optional pass/fail thresholds, and per-frame energy parity data. +The same file serves three consumers — the researcher reading the report, the +active-learning loop deciding convergence, and any dashboard rendering plots — +so quality is a recorded artifact, not an impression. + +The model under test is just a calculator: by default the one the ``train`` +stage produced (``model/manifest.json`` → a ``mace`` calculator on its +``model_path``), overridable with an explicit ``[validation.calculator]``. +Reference frames come from, in order: ``test_file`` if set, the training +holdout ``model/valid.xyz`` (frames the model never trained on), else the +latest labeled/dataset artifact. +""" + +from __future__ import annotations + +import json +import logging +from dataclasses import dataclass, field +from pathlib import Path + +import numpy as np +from ase.io import read as ase_read + +from ..calculators import make_calculator +from ..core import Structure +from ..datasets.io import read_frames +from .metrics import array_metrics, energy_metrics, force_metrics + +logger = logging.getLogger(__name__) + +REPORT_NAME = "quality_report.json" + + +@dataclass +class ValidationResult: + """Outcome of a validation run (mirrors ``quality_report.json``).""" + + metrics: dict + checks: list[dict] + passed: bool | None # None when no thresholds were configured + n_frames: int + n_failed: int + report: dict = field(default_factory=dict) + report_path: Path | None = None + + +def _as_array(value) -> np.ndarray | None: + if value is None: + return None + if isinstance(value, str): + try: + value = json.loads(value) + except json.JSONDecodeError: + return None + return np.asarray(value, dtype=float) + + +def _full_stress(value) -> np.ndarray: + """Normalize a stress (Voigt-6, 3×3, or flat-9) to a flat 3×3 tensor.""" + a = np.asarray(value, dtype=float).ravel() + if a.size == 9: + return a.reshape(3, 3) + if a.size == 6: # Voigt order: xx, yy, zz, yz, xz, xy + xx, yy, zz, yz, xz, xy = a + return np.array([[xx, xy, xz], [xy, yy, yz], [xz, yz, zz]]) + raise ValueError(f"stress with {a.size} components (expected 6 or 9)") + + +# --- reference frames -------------------------------------------------------- + +def _ref_properties(atoms) -> dict: + """Properties from training-format ``REF_*`` keys (see training/base.py).""" + props: dict = {} + if "REF_forces" in atoms.arrays: + props["forces"] = np.asarray(atoms.arrays["REF_forces"], dtype=float) + if "REF_energy" in atoms.info: + props["energy"] = float(atoms.info["REF_energy"]) + for key in ("stress", "dipole", "polarizability"): + value = _as_array(atoms.info.get(f"REF_{key}")) + if value is not None: + props[key] = value + return props + + +def load_reference_frames(path: str | Path) -> list[Structure]: + """Read labeled frames from either TrainCraft (``tc_*``) or training + (``REF_*``) extended-XYZ files.""" + images = ase_read(str(path), index=":", format="extxyz") + if not isinstance(images, list): + images = [images] + if images and any( + k.startswith("REF_") for k in (*images[0].info, *images[0].arrays) + ): + return [Structure(atoms=a, properties=_ref_properties(a)) for a in images] + return read_frames(path) + + +# --- model under test -------------------------------------------------------- + +def resolve_calculator(cfg, model_manifest: Path): + """The model to validate: explicit ``[validation.calculator]``, else the + model the ``train`` stage recorded in ``model/manifest.json``.""" + if cfg.calculator is not None: + return cfg.calculator + if model_manifest.exists(): + manifest = json.loads(model_manifest.read_text()) + model_path = manifest.get("model_path") + if model_path: + from ..config.models import MaceCalc + + return MaceCalc(model_path=model_path) + raise ValueError( + "validation needs a model to test: set [validation.calculator] explicitly, " + "or run a [training] stage first so the trained model is picked up from " + f"{model_manifest}" + ) + + +# --- the run ------------------------------------------------------------------ + +def _apply_thresholds(metrics: dict, thresholds: dict) -> tuple[list[dict], bool | None]: + flat = {k: v for k, v in metrics.items() if isinstance(v, (int, float))} + checks = [] + for name, limit in sorted(thresholds.items()): + if name not in flat: + raise ValueError( + f"unknown threshold metric {name!r}; available: {sorted(flat)}" + ) + value = flat[name] + checks.append( + {"metric": name, "value": value, "threshold": limit, "passed": value <= limit} + ) + passed = all(c["passed"] for c in checks) if checks else None + return checks, passed + + +def run_validation(frames: list[Structure], calc_cfg, cfg, *, out_dir=None) -> ValidationResult: + """Predict every reference property on ``frames`` with ``calc_cfg`` and + compare; write ``quality_report.json`` under ``out_dir`` when given. + + A frame whose core (energy/forces) prediction fails is skipped and recorded, + consistent with the labeling stage; optional properties (stress, dipole, + polarizability) that the calculator cannot produce are dropped per property. + """ + if cfg.max_frames is not None: + frames = frames[: cfg.max_frames] + if not frames: + raise ValueError("validation has no reference frames to compare against") + + calc = make_calculator(calc_cfg) + requested = set(cfg.properties) if cfg.properties else None + + def want(prop: str) -> bool: + return requested is None or prop in requested + + e_ref: list[float] = [] + e_pred: list[float] = [] + n_atoms: list[int] = [] + f_ref: list[np.ndarray] = [] + f_pred: list[np.ndarray] = [] + f_rmse_per_frame: list[float] = [] + symbols: list[list[str]] = [] + tensor_pairs: dict[str, list[tuple[np.ndarray, np.ndarray]]] = {} + failures: list[dict] = [] + + for i, s in enumerate(frames): + ref = s.properties + atoms = s.to_ase(with_properties=False) + atoms.calc = calc + try: + ref_e = ref.get("energy") + if want("energy") and ref_e is not None: + e_pred.append(float(atoms.get_potential_energy())) + e_ref.append(float(ref_e)) + n_atoms.append(len(atoms)) + ref_f = _as_array(ref.get("forces")) + if want("forces") and ref_f is not None: + pred_f = np.asarray(atoms.get_forces()) + f_pred.append(pred_f) + f_ref.append(ref_f) + symbols.append(atoms.get_chemical_symbols()) + f_rmse_per_frame.append(float(np.sqrt(np.mean((pred_f - ref_f) ** 2)))) + except Exception as exc: + failures.append({"frame": i, "error": f"{type(exc).__name__}: {exc}"}) + logger.warning("validation frame %d failed, skipping: %s", i, exc) + continue + + # Optional tensor properties: drop per property if the calculator + # cannot produce them, without voiding the frame's E/F comparison. + for prop in ("stress", "dipole", "polarizability"): + ref_value = _as_array(ref.get(prop)) + if not want(prop) or ref_value is None: + continue + try: + if prop == "stress": + if not atoms.get_pbc().any(): + continue + pair = (_full_stress(ref_value), _full_stress(atoms.get_stress())) + elif prop == "dipole": + pair = (ref_value.ravel(), np.asarray(atoms.get_dipole_moment()).ravel()) + else: + pol = getattr(calc, "results", {}).get("polarizability") + if pol is None: + continue + pair = (ref_value.ravel(), np.asarray(pol).ravel()) + except Exception as exc: + logger.debug("frame %d: no %s from calculator (%s)", i, prop, exc) + continue + tensor_pairs.setdefault(prop, []).append(pair) + + metrics: dict = {} + if e_ref: + metrics.update(energy_metrics(e_ref, e_pred, n_atoms)) + if f_ref: + metrics.update(force_metrics(f_ref, f_pred, symbols)) + for prop, pairs in tensor_pairs.items(): + metrics.update(array_metrics(prop, [r for r, _ in pairs], [p for _, p in pairs])) + + if not metrics: + first = failures[0]["error"] if failures else "no reference properties found" + raise RuntimeError( + f"validation produced no comparable predictions over {len(frames)} frames " + f"({first})" + ) + + checks, passed = _apply_thresholds(metrics, cfg.thresholds) + + report = { + "calculator": calc_cfg.model_dump(), + "n_frames": len(frames), + "n_compared": len(frames) - len(failures), + "n_failed": len(failures), + "failures": failures, + "properties": sorted( + {m.split("_")[0] for m in metrics if isinstance(metrics[m], (int, float))} + ), + "metrics": metrics, + "thresholds": dict(cfg.thresholds), + "checks": checks, + "passed": passed, + "parity": { + "energy": [[r, p] for r, p in zip(e_ref, e_pred, strict=True)], + "n_atoms": n_atoms, + "forces_rmse_per_frame": f_rmse_per_frame, + }, + } + + report_path = None + if out_dir is not None: + out_dir = Path(out_dir) + out_dir.mkdir(parents=True, exist_ok=True) + report_path = out_dir / REPORT_NAME + report_path.write_text(json.dumps(report, indent=2)) + + return ValidationResult( + metrics=metrics, + checks=checks, + passed=passed, + n_frames=len(frames), + n_failed=len(failures), + report=report, + report_path=report_path, + ) diff --git a/tests/test_validation.py b/tests/test_validation.py new file mode 100644 index 0000000..0db2e20 --- /dev/null +++ b/tests/test_validation.py @@ -0,0 +1,201 @@ +from __future__ import annotations + +import json + +import numpy as np +import pytest + +from traincraft import label_frames, run_pipeline, run_validation, write_frames +from traincraft.config.models import ( + CrystalBuilder, + EmtCalc, + GeometryConfig, + LabelingConfig, + MaceCalc, + MdSampling, + RunConfig, + SelectionConfig, + TrainCraftConfig, + ValidationConfig, +) +from traincraft.datasets import read_frames +from traincraft.geometry import build_geometry +from traincraft.training.base import write_training_xyz +from traincraft.validation import load_reference_frames, resolve_calculator +from traincraft.validation.metrics import array_metrics, energy_metrics, force_metrics + +# EMT plays both roles here: it labels the references and acts as the "model +# under test", so a self-consistent validation must score ~zero error. + + +def _labeled_cu_frames(n=3): + base = build_geometry( + GeometryConfig(builder=CrystalBuilder(name="Cu", crystalstructure="fcc", a=3.6, cubic=True)) + ) + frames = [] + for i in range(n): + s = base.copy() + s.atoms.rattle(0.02, seed=i) + frames.append(s) + return label_frames(frames, EmtCalc()) + + +# --- metrics ----------------------------------------------------------------- + +def test_energy_metrics_known_values(): + m = energy_metrics(ref=[0.0, 0.0], pred=[1.0, -1.0], n_atoms=[2, 2]) + assert m["energy_rmse"] == pytest.approx(1.0) + assert m["energy_mae"] == pytest.approx(1.0) + assert m["energy_rmse_per_atom"] == pytest.approx(0.5) + assert m["energy_mae_per_atom"] == pytest.approx(0.5) + + +def test_force_metrics_by_element(): + ref = [np.zeros((2, 3))] + pred = [np.array([[0.0, 0.0, 0.0], [3.0, 0.0, 0.0]])] # only the O atom is off + m = force_metrics(ref, pred, symbols=[["Cu", "O"]]) + assert m["forces_rmse_by_element"]["Cu"] == pytest.approx(0.0) + assert m["forces_rmse_by_element"]["O"] == pytest.approx(np.sqrt(3.0)) + assert m["forces_mae"] == pytest.approx(0.5) + + +def test_array_metrics_flattens_tensors(): + m = array_metrics("stress", [np.zeros((3, 3))], [np.full((3, 3), 2.0)]) + assert m["stress_rmse"] == pytest.approx(2.0) + assert m["stress_mae"] == pytest.approx(2.0) + + +# --- run_validation ---------------------------------------------------------- + +def test_self_consistent_model_scores_zero_and_passes(tmp_path): + frames = _labeled_cu_frames(3) + cfg = ValidationConfig( + calculator=EmtCalc(), + thresholds={"energy_mae": 1e-8, "forces_rmse": 1e-8}, + ) + result = run_validation(frames, EmtCalc(), cfg, out_dir=tmp_path) + assert result.passed is True + assert result.n_frames == 3 + assert result.n_failed == 0 + assert result.metrics["energy_rmse"] == pytest.approx(0.0, abs=1e-10) + assert "Cu" in result.metrics["forces_rmse_by_element"] + assert "stress_rmse" in result.metrics # periodic Cu: EMT produces stress + + report = json.loads((tmp_path / "quality_report.json").read_text()) + assert report["passed"] is True + assert report["metrics"]["forces_rmse"] == pytest.approx(0.0, abs=1e-10) + assert len(report["parity"]["energy"]) == 3 + assert len(report["checks"]) == 2 + + +def test_bad_reference_fails_threshold(): + frames = _labeled_cu_frames(2) + for s in frames: + s.properties["energy"] = float(s.properties["energy"]) + 1.0 + cfg = ValidationConfig(calculator=EmtCalc(), thresholds={"energy_mae": 0.5}) + result = run_validation(frames, EmtCalc(), cfg) + assert result.metrics["energy_mae"] == pytest.approx(1.0, abs=1e-6) + assert result.passed is False + assert result.checks[0]["passed"] is False + + +def test_no_thresholds_means_passed_is_none(): + cfg = ValidationConfig(calculator=EmtCalc()) + result = run_validation(_labeled_cu_frames(2), EmtCalc(), cfg) + assert result.passed is None + assert result.checks == [] + + +def test_unknown_threshold_metric_raises(): + cfg = ValidationConfig(calculator=EmtCalc(), thresholds={"engery_mae": 0.1}) # typo + with pytest.raises(ValueError, match="unknown threshold metric"): + run_validation(_labeled_cu_frames(2), EmtCalc(), cfg) + + +def test_max_frames_caps_the_comparison(): + cfg = ValidationConfig(calculator=EmtCalc(), max_frames=1) + result = run_validation(_labeled_cu_frames(3), EmtCalc(), cfg) + assert result.n_frames == 1 + + +# --- reference loading ------------------------------------------------------- + +def test_load_reference_frames_reads_training_ref_keys(tmp_path): + frames = _labeled_cu_frames(2) + path = write_training_xyz(tmp_path / "valid.xyz", frames) + loaded = load_reference_frames(path) + assert len(loaded) == 2 + for orig, back in zip(frames, loaded, strict=True): + assert back.properties["energy"] == pytest.approx(orig.properties["energy"], abs=1e-8) + np.testing.assert_allclose( + back.properties["forces"], orig.properties["forces"], atol=1e-7 + ) + + +def test_load_reference_frames_reads_tc_keys(tmp_path): + frames = _labeled_cu_frames(2) + path = write_frames(tmp_path / "labeled.extxyz", frames) + loaded = load_reference_frames(path) + assert loaded[0].properties["energy"] == pytest.approx(frames[0].properties["energy"]) + + +def test_read_frames_roundtrips_arrays_not_strings(tmp_path): + frames = _labeled_cu_frames(1) + path = write_frames(tmp_path / "f.extxyz", frames) + back = read_frames(path)[0] + assert isinstance(back.properties["stress"], np.ndarray) # was a JSON string before + np.testing.assert_allclose( + np.asarray(back.properties["stress"]).ravel(), + np.asarray(frames[0].properties["stress"]).ravel(), + atol=1e-6, + ) + + +# --- calculator resolution --------------------------------------------------- + +def test_resolve_calculator_prefers_explicit(tmp_path): + cfg = ValidationConfig(calculator=EmtCalc()) + assert resolve_calculator(cfg, tmp_path / "manifest.json").type == "emt" + + +def test_resolve_calculator_defaults_to_trained_model(tmp_path): + manifest = tmp_path / "manifest.json" + manifest.write_text(json.dumps({"model_path": "/models/finetuned.model"})) + calc = resolve_calculator(ValidationConfig(), manifest) + assert isinstance(calc, MaceCalc) + assert calc.model_path == "/models/finetuned.model" + + +def test_resolve_calculator_without_model_raises(tmp_path): + with pytest.raises(ValueError, match="validation needs a model"): + resolve_calculator(ValidationConfig(), tmp_path / "manifest.json") + + +# --- pipeline integration ---------------------------------------------------- + +def test_pipeline_runs_validation_stage(tmp_path): + cfg = TrainCraftConfig( + run=RunConfig(name="val", outdir=str(tmp_path), seed=1), + geometry=GeometryConfig( + builder=CrystalBuilder( + name="Cu", crystalstructure="fcc", a=3.6, cubic=True, supercell=(2, 2, 2) + ) + ), + calculator=EmtCalc(), + sampling=MdSampling(temperature=300.0, steps=50, interval=10), + selection=SelectionConfig(budget=3), + labeling=LabelingConfig(calculator=EmtCalc()), + validation=ValidationConfig( + calculator=EmtCalc(), + thresholds={"energy_mae_per_atom": 1e-6, "forces_rmse": 1e-6}, + ), + ) + summary = run_pipeline(cfg) + assert summary["validation_passed"] is True + report = json.loads((tmp_path / "val" / "validation" / "quality_report.json").read_text()) + assert report["n_frames"] > 0 + assert report["metrics"]["forces_rmse"] == pytest.approx(0.0, abs=1e-8) + + # Rerun: the validate stage must be cached (same key), not recomputed. + summary2 = run_pipeline(cfg) + assert summary2["validation_passed"] is True From 330dc456761e0dc00855d1c28a3e08343db03ac7 Mon Sep 17 00:00:00 2001 From: David Abbasi Perez Date: Tue, 7 Jul 2026 17:33:12 +0200 Subject: [PATCH 03/15] docs: teach the skill, CLI/API reference, examples (26) and tutorials the new validate stage and labeling failure semantics Co-Authored-By: Claude Fable 5 Claude-Session: https://claude.ai/code/session_01V6f4Z4uLdysBeehYfbQ56k --- docs/concepts/training.md | 8 ++++- docs/how-to/own-mace-model.md | 9 +++--- docs/reference/api.md | 15 ++++++++++ docs/reference/cli.md | 12 +++++--- docs/tutorials/10-training.md | 6 ++-- examples/26_validate_model.toml | 52 +++++++++++++++++++++++++++++++++ pixi.lock | 2 +- pyproject.toml | 1 + skills/traincraft/SKILL.md | 23 +++++++++++++-- 9 files changed, 113 insertions(+), 15 deletions(-) create mode 100644 examples/26_validate_model.toml diff --git a/docs/concepts/training.md b/docs/concepts/training.md index 4b9f7ad..8200189 100644 --- a/docs/concepts/training.md +++ b/docs/concepts/training.md @@ -24,7 +24,7 @@ same pattern as calculators and samplers. ## Where training sits in the pipeline ``` -geometry → sample → select → label → dataset → TRAIN +geometry → sample → select → label → dataset → TRAIN → validate ``` `train` consumes the dataset artifact (or, if no `[dataset]` section, the @@ -33,6 +33,12 @@ labelled frames) and writes a model tree under `runs//model/`: `logs/`, and a `manifest.json` recording the foundation model, heads, E0s, the exact rendered command, and the split sizes. +The optional `validate` stage then measures the freshly trained model against +the holdout `valid.xyz` and writes `validation/quality_report.json` — parity +metrics with optional pass/fail thresholds (see +[`[validation]`](../reference/config.md#validation)). Don't call a model good +without it. + On HPC the stage runs as a **GPU step** (`--nv`, `traincraft-mlip.sif`); the command is injected from `$TRAINCRAFT_MACE_TRAIN_COMMAND` so the science stays container-agnostic (the same mechanism as the DFT labelers — see diff --git a/docs/how-to/own-mace-model.md b/docs/how-to/own-mace-model.md index 2eb9210..bb77e9d 100644 --- a/docs/how-to/own-mace-model.md +++ b/docs/how-to/own-mace-model.md @@ -78,15 +78,16 @@ calc = tc.make_calculator(MaceCalc( ``` Iteration 1 - traincraft run seed_run.toml ← generate → select → label → dataset → TRAIN - → runs/seed_run/model/model_v1.model + traincraft run seed_run.toml ← generate → select → label → dataset → TRAIN → validate + → runs/seed_run/model/model_v1.model + validation/quality_report.json Iteration 2 set [calculator].model_path = .../model_v1.model ← explore with your model - traincraft run iter2.toml ← MACE-driven explore → select → label → TRAIN + traincraft run iter2.toml ← MACE-driven explore → select → label → TRAIN → validate → model_v2.model -…repeat until validation error converges +…repeat until the quality report converges (add a [validation] section with +thresholds; the report records pass/fail per metric) ``` Phase 4 automates this loop (committee uncertainty selection + convergence diff --git a/docs/reference/api.md b/docs/reference/api.md index 0758a92..f740176 100644 --- a/docs/reference/api.md +++ b/docs/reference/api.md @@ -19,6 +19,9 @@ structure = tc.build_geometry(cfg.geometry) calc = tc.make_calculator(cfg.calculator) frames = tc.run_sampling(structure, calc, job, cfg.sampling) selected = tc.run_funnel(frames, cfg.selection) +labeled = tc.label_frames(selected, cfg.labeling.calculator, out_dir=out) +result = tc.run_training(labeled, cfg.training, job) +quality = tc.run_validation(labeled, calc_cfg, cfg.validation, out_dir=out) summary = tc.run_pipeline(cfg) # the whole pipeline # Dataset IO @@ -126,3 +129,15 @@ frames = tc.read_frames("dataset.extxyz") ::: traincraft.datasets.io.write_frames ::: traincraft.datasets.io.read_frames + +--- + +## Validation + +::: traincraft.validation.validate.run_validation + +::: traincraft.validation.validate.ValidationResult + +::: traincraft.validation.validate.load_reference_frames + +::: traincraft.validation.validate.resolve_calculator diff --git a/docs/reference/cli.md b/docs/reference/cli.md index 592f5fe..a677880 100644 --- a/docs/reference/cli.md +++ b/docs/reference/cli.md @@ -28,7 +28,7 @@ traincraft run CONFIG [--force] 1. Loads and validates `CONFIG` via pydantic. 2. Creates the workspace directory (`runs//`). 3. Runs each active stage in order: geometry → sampling → selection → labeling → - dataset → training (only the sections you declared run). + dataset → training → validation (only the sections you declared run). 4. Prints a summary to stdout. !!! note "Slurm routing" @@ -82,7 +82,7 @@ traincraft stage NAME CONFIG [--force] | Argument | Description | |---|---| -| `NAME` | One of: `geometry`, `sample`, `select`, `label`, `dataset`, `train` | +| `NAME` | One of: `geometry`, `sample`, `select`, `label`, `dataset`, `train`, `validate` | | `CONFIG` | Path to a `.toml` file | | `--force` | Recompute even if the stage's artifact already exists | @@ -97,6 +97,9 @@ stage 'train': 42 frames ``` The `train` stage writes `runs//model/.model` and a `manifest.json`. +The `validate` stage writes `runs//validation/quality_report.json` — +parity metrics + threshold checks for the trained model (see +[`[validation]`](config.md#validation)). See [Tutorial 10 · Training](../tutorials/10-training.md). --- @@ -114,8 +117,9 @@ traincraft submit CONFIG [--dry-run] |---|---| | `--dry-run` | Write the sbatch scripts but don't submit | -The GPU stages (`sample`, `train`) run in `traincraft-mlip.sif` with `--nv`; the -DFT `label` stage injects the engine command. See [Run on HPC](../how-to/hpc.md). +The GPU stages (`sample`, `train`, `validate`) run in `traincraft-mlip.sif` with +`--nv`; the DFT `label` stage injects the engine command. See +[Run on HPC](../how-to/hpc.md). --- diff --git a/docs/tutorials/10-training.md b/docs/tutorials/10-training.md index dbeeeaf..84c9608 100644 --- a/docs/tutorials/10-training.md +++ b/docs/tutorials/10-training.md @@ -88,10 +88,12 @@ node (more on that at the end). ## Where training sits -Training is the final stage of the spine — it consumes the dataset: +Training consumes the dataset; an optional `validate` stage then scores the +result (add a `[validation]` section — see the +[config reference](../reference/config.md#validation)): ``` -geometry → sample → select → label → dataset → TRAIN +geometry → sample → select → label → dataset → TRAIN → validate ``` Add `[training]` and `traincraft run` will execute it after the dataset is diff --git a/examples/26_validate_model.toml b/examples/26_validate_model.toml new file mode 100644 index 0000000..a903cf5 --- /dev/null +++ b/examples/26_validate_model.toml @@ -0,0 +1,52 @@ +[run] +name = "validate_model" +seed = 9 +outdir = "runs" +# Full spine + VALIDATION: build → sample → select → label → validate. +# The validate stage measures a model against the reference labels and writes +# validation/quality_report.json (RMSE/MAE per property, per-element forces, +# threshold checks, overall pass/fail). +# +# Here EMT plays both roles — it labels the references AND is the "model under +# test" — so the errors are ~zero and the thresholds pass; the point is the +# mechanics with zero extra deps. On a real run you omit [validation.calculator] +# entirely: it then defaults to the model the [training] stage just produced +# (from model/manifest.json) and validates on the training holdout valid.xyz. +# Run with: pixi run example-26 + +[geometry] + +[geometry.builder] +type = "crystal" +name = "Cu" +crystalstructure = "fcc" +a = 3.61 +cubic = true +supercell = [2, 2, 2] + +[calculator] +type = "emt" + +[sampling] +type = "md" +temperature = 600.0 +steps = 200 +interval = 20 +timestep = 2.0 + +[selection] +steps = ["physicality", "dedup", "diversity"] +budget = 5 +min_distance = 0.7 + +[labeling.calculator] +type = "emt" # real runs: type = "fhi_aims" or "qe" + +[validation] +# real runs: omit this calculator to test the freshly trained MACE model +[validation.calculator] +type = "emt" + +[validation.thresholds] +forces_rmse = 0.05 # eV/Å +energy_mae_per_atom = 0.005 # eV/atom diff --git a/pixi.lock b/pixi.lock index f7897d9..36fce95 100644 --- a/pixi.lock +++ b/pixi.lock @@ -4395,7 +4395,7 @@ packages: - pypi: ./ name: traincraft version: 0.1.0 - sha256: 54d85fd11a45d73b977cf9c7e485cd98387a3a355931b08f7c645a541bd8de27 + sha256: b3cc69150628c3160b647680cacc8caeaebb9616ad9d40a825b80bfb84b3e3fa requires_dist: - ase>=3.22 - numpy>=1.23 diff --git a/pyproject.toml b/pyproject.toml index 470debc..14960ee 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -152,6 +152,7 @@ example-22 = { cmd = "traincraft run examples/22_filled_nanotube.toml", descript example-23 = { cmd = "traincraft run examples/23_solvent_mixture.toml", description = "Water/ethanol solvent blend by ratio (liquid mixture) + xTB MD (needs science env)" } example-24 = { cmd = "traincraft run examples/24_cuau_alloy_md.toml", description = "Random Cu/Au substitutional alloy (composition) + EMT MD (no extra deps)" } example-25 = { cmd = "traincraft run examples/25_pes_scan.toml", description = "Deterministic CO/Cu(111) binding-curve PES scan (scan sampler) + EMT (no extra deps)" } +example-26 = { cmd = "traincraft run examples/26_validate_model.toml", description = "Build->...->label->VALIDATE (quality_report.json with threshold checks; EMT stand-in, no extra deps)" } # Docs tasks live on the `docs` feature so they only exist in the `docs` # environment — `pixi run docs-serve` then auto-selects that env (no `-e docs`). diff --git a/skills/traincraft/SKILL.md b/skills/traincraft/SKILL.md index 4fbc4cc..7eff2dc 100644 --- a/skills/traincraft/SKILL.md +++ b/skills/traincraft/SKILL.md @@ -3,7 +3,8 @@ name: traincraft description: >- Act as a TrainCraft expert — translate plain-language requests into validated TOML configs and run the MLIP-dataset pipeline (geometry → sample → select → - label → dataset → train), using the correct pixi environment every time. + label → dataset → train → validate), using the correct pixi environment every + time. --- # TrainCraft Expert Skill @@ -90,6 +91,15 @@ Map the user's words to config keys (run `traincraft plugins` for the live list) displacements). - **Selection** (`[selection] steps = ...`): default funnel `["physicality", "dedup", "diversity"]` with a `budget`. +- **Labeling** (`[labeling]`): a `[labeling.calculator]` (usually DFT) labels the + *selected* frames. Failed frames are skipped + quarantined by default + (`on_error = "skip"`); reruns resume — completed frames are reused, failed ones + retried. Check `labeled_dft/manifest.json` (`n_failed`, `failures`) after a run. +- **Validation** (`[validation]`): measures a model against reference labels → + `validation/quality_report.json` (RMSE/MAE per property, per-element forces, + optional `thresholds` → `passed`). Defaults to the model `[training]` just + produced and its holdout `valid.xyz`. **Read `quality_report.json` and report + the metrics + pass/fail to the user** — never claim a model is good without it. ## ⚠️ Gotchas (learned the hard way) @@ -115,9 +125,14 @@ Map the user's words to config keys (run `traincraft plugins` for the live list) - `structures/initial.extxyz` — the built geometry. - `candidates/candidates.extxyz` (+ `md.traj` / `mc.traj`) — sampler output. - `selected/selected.extxyz` — what survived the selection funnel. -- `labeled_dft/labeled.extxyz` (+ `manifest.json`) — DFT-labeled frames. +- `labeled_dft/labeled.extxyz` (+ `manifest.json`) — DFT-labeled frames. The + manifest records `n_attempted`/`n_failed`/`n_reused` and per-frame errors; + failed frames leave their input quarantined in `frame_XXXX/input.extxyz`. - `dataset.extxyz` — the assembled dataset at the run root. -- `model/.model` (+ `manifest.json`) — a trained/fine-tuned MACE model. +- `model/.model` (+ `manifest.json`, `valid.xyz` holdout) — a + trained/fine-tuned MACE model. +- `validation/quality_report.json` — parity metrics, threshold checks, and the + overall `passed` verdict for the validated model. ## 🖼 Visualising (headless-VM friendly) @@ -141,4 +156,6 @@ traincraft plugins # list builders/calculators/samplers traincraft new # write a starter config traincraft validate # validate + show resolved stages pixi run -e traincraft run # run the pipeline +pixi run -e traincraft stage # one stage standalone + # (geometry|sample|select|label|dataset|train|validate) ``` From 17151c9c1e40c14a668ab05d62d30af543411fa1 Mon Sep 17 00:00:00 2001 From: David Abbasi Perez Date: Tue, 7 Jul 2026 18:14:46 +0200 Subject: [PATCH 04/15] feat(labeling): replace per-frame directories with append-only receipts/journal/quarantine files so 100k+-frame runs stay Lustre-safe Co-Authored-By: Claude Fable 5 Claude-Session: https://claude.ai/code/session_01V6f4Z4uLdysBeehYfbQ56k --- docs/concepts/calculators.md | 30 ++++-- docs/getting-started/end-to-end.md | 2 +- docs/reference/config.md | 17 ++-- src/traincraft/labeling.py | 157 +++++++++++++++++++---------- tests/test_labeling.py | 44 +++++--- 5 files changed, 164 insertions(+), 86 deletions(-) diff --git a/docs/concepts/calculators.md b/docs/concepts/calculators.md index 2672e0d..c44ea21 100644 --- a/docs/concepts/calculators.md +++ b/docs/concepts/calculators.md @@ -118,23 +118,31 @@ This produces, under the run workspace: labeled_dft/ labeled.extxyz # frames with E/F/stress(+dipole/pol) and origin=dft_labeled manifest.json # level of theory, property set, counts (attempted/failed/reused), failures - frame_0000/ … # per-frame work dirs (so file-IO calcs don't collide) - result.json # per-frame receipt: status + fingerprint (+ error on failure) - labeled.extxyz # the frame's own result (reused on rerun) + receipts.jsonl # one line per attempt: fingerprint, status, wall time, error + done.extxyz # labeled frames journaled as they complete (the resume cache) + failed.extxyz # quarantined inputs of failed frames + work/ # single reusable scratch dir for file-IO calcs, wiped between frames + failed/frame_N/ … # snapshot of work/ — only for frames that failed ``` -Each labeled frame is tagged `origin="dft_labeled"` with its `level_of_theory`, -so the expensive data stays cleanly separable from the cheap, ML-generated points +The bookkeeping is a **fixed set of append-only files**, never a directory per +frame: a 10⁶-frame labeling run adds zero directories (plus one debug snapshot +per *failure*), which is what keeps Lustre metadata servers happy. Each labeled +frame is tagged `origin="dft_labeled"` with its `level_of_theory`, so the +expensive data stays cleanly separable from the cheap, ML-generated points (see [Provenance](provenance.md)). The dataset is built from these labeled frames. **Failures don't kill the batch.** SCF non-convergence and walltime kills are routine at scale, so by default (`on_error = "skip"` in `[labeling]`) a failed -frame is quarantined — its input written to `frame_XXXX/input.extxyz`, the error -recorded in `manifest.json` — and labeling continues; set `on_error = "raise"` -to abort on the first failure instead. If every frame fails, the stage raises -regardless. **Reruns resume**: each frame's `result.json` receipt fingerprints -its geometry + level of theory, so completed frames are reused and only failed -(or changed) frames are recomputed. +frame is quarantined — its input appended to `failed.extxyz`, the error recorded +in `receipts.jsonl` and `manifest.json`, the DFT scratch dir snapshotted to +`failed/frame_N/` for inspection — and labeling continues; set `on_error = +"raise"` to abort on the first failure instead. If every frame fails, the stage +raises regardless. **Reruns resume**: `done.extxyz` journals every completed +frame keyed by a fingerprint of its geometry + level of theory, so completed +frames are reused and only failed (or changed) frames are recomputed. The +journal is a pure cache — deleting it only costs recomputation. While labeling +runs, `traincraft status ` shows live progress from `receipts.jsonl`. > Tip: to *try the mechanics* with zero deps, set `[labeling.calculator] type = > "emt"` — EMT stands in for DFT and produces E/F/stress. `examples/18` does this. diff --git a/docs/getting-started/end-to-end.md b/docs/getting-started/end-to-end.md index 79f8581..55715dc 100644 --- a/docs/getting-started/end-to-end.md +++ b/docs/getting-started/end-to-end.md @@ -103,7 +103,7 @@ Run it: ```bash pixi run example-18 -ls runs/label_after_select/labeled_dft/ # labeled.extxyz manifest.json frame_0000/ … +ls runs/label_after_select/labeled_dft/ # labeled.extxyz manifest.json receipts.jsonl done.extxyz work/ ``` The `[labeling]` section is the key addition: it labels the **selected** frames diff --git a/docs/reference/config.md b/docs/reference/config.md index fde988e..5e88f81 100644 --- a/docs/reference/config.md +++ b/docs/reference/config.md @@ -501,7 +501,7 @@ cheap `[calculator]` that drives sampling. Presence of this section enables the | Field | Type | Default | Description | |---|---|---|---| | `calculator` | calculator config | required | A `[labeling.calculator]` sub-table; usually `fhi_aims` or `qe` (any calculator works — `emt` stands in for DFT in demos) | -| `on_error` | `"skip" \| "raise"` | `"skip"` | What one failed frame does to the batch. `"skip"` quarantines the frame's input under its `frame_XXXX/` dir, records the error in `manifest.json`, and continues; `"raise"` aborts on the first failure. If **every** frame fails the stage raises regardless. | +| `on_error` | `"skip" \| "raise"` | `"skip"` | What one failed frame does to the batch. `"skip"` quarantines the frame's input in `failed.extxyz`, records the error in `receipts.jsonl` + `manifest.json`, and continues; `"raise"` aborts on the first failure. If **every** frame fails the stage raises regardless. | ```toml [labeling] @@ -514,12 +514,15 @@ species_defaults = "tight" properties = ["polarizability"] # E/F/stress always; + dipole/polarizability on request ``` -Each frame runs in its own `frame_XXXX/` work dir and writes a `result.json` -receipt (status + a fingerprint of the frame geometry and level of theory) plus -`labeled.extxyz` on success. **Reruns resume**: frames whose receipt matches are -reused without recomputation, failed frames are retried, and `manifest.json` -reports `n_attempted` / `n_frames` / `n_failed` / `n_reused` with per-frame -error messages. +Bookkeeping is a fixed set of append-only files (Lustre-safe at 10⁵–10⁶ +frames — no directory per frame): `receipts.jsonl` gets one line per attempt +(fingerprint of geometry + level of theory, status, wall time, error) and +`done.extxyz` journals each labeled frame as it completes. **Reruns resume**: +journaled frames whose fingerprint still matches are reused without +recomputation, failed frames are retried, and `manifest.json` reports +`n_attempted` / `n_frames` / `n_failed` / `n_reused` with per-frame error +messages. File-IO DFT codes run in one reusable `work/` scratch dir, snapshotted +to `failed/frame_N/` when a frame fails. See [Calculators & DFT Labeling](../concepts/calculators.md) for the DFT calculator fields and the environment-injected run command. diff --git a/src/traincraft/labeling.py b/src/traincraft/labeling.py index 0273246..d1256c2 100644 --- a/src/traincraft/labeling.py +++ b/src/traincraft/labeling.py @@ -9,16 +9,26 @@ At scale, partial success is the *normal* outcome: SCF non-convergence, walltime kills and bad initial guesses are routine. So failures are isolated per frame — ``on_error="skip"`` (the default) quarantines the failed frame's input, records -the error in the manifest, and keeps going; ``"raise"`` aborts on first failure. -If every frame fails, the stage raises regardless (an empty artifact would only -hide a broken setup). - -Each frame is computed in its own sub-directory (``frame_0000/`` …) so file-IO -calculators (FHI-aims, QE) don't clobber one another, and each writes a -``result.json`` receipt plus its ``labeled.extxyz`` on success. A rerun reuses -completed frames whose receipt matches the current frame + level of theory, and -retries failed ones — so a crashed or partially failed labeling run resumes -instead of recomputing everything. +the error, and keeps going; ``"raise"`` aborts on first failure. If every frame +fails, the stage raises regardless (an empty artifact would only hide a broken +setup). + +Bookkeeping is sized for Lustre-scale runs (10^5–10^6 frames): a fixed set of +**append-only files** instead of a directory per frame, so the file count stays +O(1) in the number of frames (plus one debug snapshot per *failure*): + + receipts.jsonl one line per attempt (fingerprint, status, wall time, error) + — doubles as a live progress feed for ``traincraft status`` + done.extxyz labeled frames journaled as they complete (the resume cache) + failed.extxyz quarantined inputs of failed frames + work/ single reusable scratch dir for file-IO calculators + (FHI-aims, QE), wiped between frames + failed/frame_N/ snapshot of ``work/`` taken only when a frame fails + +A rerun reuses journaled frames whose fingerprint (geometry + level of theory) +still matches and retries the rest — a crashed or partially failed labeling run +resumes instead of recomputing everything. ``done.extxyz`` is a pure cache: +deleting it is always safe and only costs recomputation. """ from __future__ import annotations @@ -26,7 +36,9 @@ import hashlib import json import logging +import shutil import time +from datetime import datetime, timezone from pathlib import Path import numpy as np @@ -37,6 +49,11 @@ logger = logging.getLogger(__name__) +RECEIPTS_NAME = "receipts.jsonl" +JOURNAL_NAME = "done.extxyz" +QUARANTINE_NAME = "failed.extxyz" +_FP_KEY = "label_fp" # fingerprint carried inside journal/quarantine frames + def _level_of_theory(calc_cfg) -> dict: data = calc_cfg.model_dump() @@ -53,24 +70,44 @@ def _fingerprint(s: Structure, level: dict, extra_props: list[str]) -> str: return hashlib.sha256(blob).hexdigest()[:16] -def _write_result(frame_dir: Path, record: dict) -> None: - (frame_dir / "result.json").write_text(json.dumps(record, indent=2)) +def _append_receipt(out_dir: Path, record: dict) -> None: + record = {"ts": datetime.now(timezone.utc).isoformat(timespec="seconds"), **record} + with (out_dir / RECEIPTS_NAME).open("a") as fh: + fh.write(json.dumps(record) + "\n") -def _reuse(frame_dir: Path, fingerprint: str) -> Structure | None: - """The frame's previous result, if it succeeded under the same fingerprint.""" - result_file = frame_dir / "result.json" - labeled_file = frame_dir / "labeled.extxyz" - if not (result_file.exists() and labeled_file.exists()): - return None +def _journal_cache(out_dir: Path) -> dict[str, Structure]: + """Previously labeled frames by fingerprint (empty if no/unreadable journal).""" + journal = out_dir / JOURNAL_NAME + if not journal.exists(): + return {} try: - record = json.loads(result_file.read_text()) - except json.JSONDecodeError: - return None - if record.get("status") != "ok" or record.get("fingerprint") != fingerprint: - return None - frames = read_frames(labeled_file) - return frames[0] if frames else None + frames = read_frames(journal) + except Exception: # truncated by a crash mid-write: recompute, don't die + logger.warning("unreadable labeling journal %s; recomputing all frames", journal) + return {} + cache: dict[str, Structure] = {} + for s in frames: + fp = s.properties.pop(_FP_KEY, None) + if fp: + cache[str(fp)] = s + return cache + + +def _clear_dir(path: Path) -> None: + for child in path.iterdir(): + if child.is_dir() and not child.is_symlink(): + shutil.rmtree(child) + else: + child.unlink() + + +def _quarantine(out_dir: Path, work_dir: Path | None, i: int, s: Structure, fp: str) -> None: + q = s.copy() + q.properties = {**q.properties, _FP_KEY: fp} + write_frames(out_dir / QUARANTINE_NAME, [q], append=True) + if work_dir is not None and any(work_dir.iterdir()): + shutil.copytree(work_dir, out_dir / "failed" / f"frame_{i:05d}", dirs_exist_ok=True) def _compute(atoms, calc, calc_cfg, extra_props: list[str]) -> dict: @@ -98,10 +135,11 @@ def label_frames( ) -> list[Structure]: """Label ``frames`` with ``calc_cfg``; return new ``dft_labeled`` Structures. - ``out_dir`` (a directory) enables per-frame work dirs, per-frame resume, and - a ``manifest.json`` recording the level of theory, the property set, and any - failures. ``on_error="skip"`` drops failed frames (quarantining their input - for inspection); ``"raise"`` propagates the first failure. + ``out_dir`` (a directory) enables the append-only bookkeeping described in + the module docstring: per-frame receipts, the resume journal, quarantine of + failed inputs, and a ``manifest.json`` recording the level of theory, the + property set, and any failures. ``on_error="skip"`` drops failed frames; + ``"raise"`` propagates the first failure. """ if on_error not in ("skip", "raise"): raise ValueError(f"on_error must be 'skip' or 'raise', not {on_error!r}") @@ -110,40 +148,46 @@ def label_frames( level = _level_of_theory(calc_cfg) out_dir = Path(out_dir) if out_dir is not None else None + cache: dict[str, Structure] = {} + work_dir: Path | None = None + if out_dir is not None: + out_dir.mkdir(parents=True, exist_ok=True) + cache = _journal_cache(out_dir) + work_dir = out_dir / "work" + work_dir.mkdir(exist_ok=True) + if hasattr(calc, "directory"): + calc.directory = str(work_dir) + labeled: list[Structure] = [] failures: list[dict] = [] n_reused = 0 t0 = time.perf_counter() for i, s in enumerate(frames): fingerprint = _fingerprint(s, level, extra_props) - frame_dir = None - if out_dir is not None: - frame_dir = out_dir / f"frame_{i:04d}" - previous = _reuse(frame_dir, fingerprint) - if previous is not None: - labeled.append(previous) - n_reused += 1 - logger.info("labeled %d/%d (reused previous result)", i + 1, len(frames)) - continue - frame_dir.mkdir(parents=True, exist_ok=True) - if hasattr(calc, "directory"): - calc.directory = str(frame_dir) + previous = cache.get(fingerprint) + if previous is not None: + labeled.append(previous.copy()) + n_reused += 1 + logger.info("labeled %d/%d (reused journaled result)", i + 1, len(frames)) + continue + if work_dir is not None: + _clear_dir(work_dir) atoms = s.to_ase(with_properties=False) t_frame = time.perf_counter() try: props = _compute(atoms, calc, calc_cfg, extra_props) except Exception as exc: + error = f"{type(exc).__name__}: {exc}" + if out_dir is not None: + _quarantine(out_dir, work_dir, i, s, fingerprint) + _append_receipt( + out_dir, {"i": i, "fp": fingerprint, "status": "failed", "error": error} + ) if on_error == "raise": raise - error = f"{type(exc).__name__}: {exc}" failures.append({"frame": i, "error": error}) logger.warning("frame %d/%d failed, skipping: %s", i + 1, len(frames), error) - if frame_dir is not None: - write_frames(frame_dir / "input.extxyz", [s]) - _write_result( - frame_dir, {"status": "failed", "fingerprint": fingerprint, "error": error} - ) continue new = s.copy() @@ -152,13 +196,16 @@ def label_frames( new.provenance.calculator = calc_cfg.type new.provenance.level_of_theory = level labeled.append(new) - if frame_dir is not None: - write_frames(frame_dir / "labeled.extxyz", [new]) - _write_result( - frame_dir, + if out_dir is not None: + journaled = new.copy() + journaled.properties = {**props, _FP_KEY: fingerprint} + write_frames(out_dir / JOURNAL_NAME, [journaled], append=True) + _append_receipt( + out_dir, { + "i": i, + "fp": fingerprint, "status": "ok", - "fingerprint": fingerprint, "wall_seconds": round(time.perf_counter() - t_frame, 2), }, ) @@ -183,8 +230,12 @@ def label_frames( "on_error": on_error, "wall_seconds": round(time.perf_counter() - t0, 2), "origin": "dft_labeled", + "files": { + "receipts": RECEIPTS_NAME, + "journal": JOURNAL_NAME, + "quarantine": QUARANTINE_NAME, + }, } - out_dir.mkdir(parents=True, exist_ok=True) (out_dir / "manifest.json").write_text(json.dumps(manifest, indent=2)) return labeled diff --git a/tests/test_labeling.py b/tests/test_labeling.py index 27a8cca..b044bb6 100644 --- a/tests/test_labeling.py +++ b/tests/test_labeling.py @@ -48,14 +48,21 @@ def test_label_frames_sets_properties_and_origin(): assert "stress" in s.properties # Cu bulk is periodic -def test_label_frames_writes_manifest_and_frame_dirs(tmp_path): +def test_label_frames_writes_manifest_receipts_and_journal(tmp_path): label_frames(_cu_frames(2), EmtCalc(), out_dir=tmp_path) manifest = json.loads((tmp_path / "manifest.json").read_text()) assert manifest["origin"] == "dft_labeled" assert manifest["calculator"] == "emt" assert manifest["n_frames"] == 2 assert "energy" in manifest["properties"] - assert (tmp_path / "frame_0000").is_dir() + + # Bookkeeping is a fixed set of append-only files — never a dir per frame + # (a 10^6-frame run must not create 10^6 directories on Lustre). + receipts = [json.loads(x) for x in (tmp_path / "receipts.jsonl").read_text().splitlines()] + assert len(receipts) == 2 + assert all(r["status"] == "ok" for r in receipts) + assert len(read_frames(tmp_path / "done.extxyz")) == 2 + assert not list(tmp_path.glob("frame_*")) class _FlakyEMT(EMT): @@ -91,11 +98,14 @@ def test_label_frames_skips_and_quarantines_failed_frames(tmp_path, monkeypatch) assert manifest["failures"][0]["frame"] == 1 assert "SCF did not converge" in manifest["failures"][0]["error"] - failed_dir = tmp_path / "frame_0001" - result = json.loads((failed_dir / "result.json").read_text()) - assert result["status"] == "failed" - assert (failed_dir / "input.extxyz").exists() # quarantined for inspection - assert not (failed_dir / "labeled.extxyz").exists() + quarantined = read_frames(tmp_path / "failed.extxyz") # input kept for inspection + assert len(quarantined) == 1 + receipts = [json.loads(x) for x in (tmp_path / "receipts.jsonl").read_text().splitlines()] + failed = [r for r in receipts if r["status"] == "failed"] + assert len(failed) == 1 + assert failed[0]["i"] == 1 + assert "SCF did not converge" in failed[0]["error"] + assert len(read_frames(tmp_path / "done.extxyz")) == 2 # only successes journaled def test_label_frames_on_error_raise_propagates(monkeypatch): @@ -140,16 +150,13 @@ def test_label_frames_rerun_retries_failed_frames(tmp_path, monkeypatch): assert manifest["n_failed"] == 0 -def test_label_frames_stale_fingerprint_recomputes(tmp_path, monkeypatch): +def test_label_frames_changed_geometry_recomputes(tmp_path, monkeypatch): frames = _cu_frames(2) label_frames(frames, EmtCalc(), out_dir=tmp_path) - # A receipt from a different geometry/level of theory must not be reused. - result_file = tmp_path / "frame_0000" / "result.json" - record = json.loads(result_file.read_text()) - record["fingerprint"] = "0" * 16 - result_file.write_text(json.dumps(record)) - + # A journaled result keys on geometry + level of theory: change one frame's + # geometry and only that frame is recomputed. + frames[0].atoms.rattle(0.05, seed=99) counting = _patch_calc(monkeypatch, _FlakyEMT()) labeled = label_frames(frames, EmtCalc(), out_dir=tmp_path) assert len(labeled) == 2 @@ -158,6 +165,15 @@ def test_label_frames_stale_fingerprint_recomputes(tmp_path, monkeypatch): assert manifest["n_reused"] == 1 +def test_label_frames_reused_frames_carry_no_bookkeeping_keys(tmp_path): + frames = _cu_frames(2) + label_frames(frames, EmtCalc(), out_dir=tmp_path) + labeled = label_frames(frames, EmtCalc(), out_dir=tmp_path) # all reused + for s in labeled: + assert "label_fp" not in s.properties + assert s.provenance.origin == "dft_labeled" + + def test_pipeline_labels_selected_frames(tmp_path): cfg = TrainCraftConfig( run=RunConfig(name="lbl", outdir=str(tmp_path), seed=1), From 19912651992f6e18a2442680294459d2a4bfc92e Mon Sep 17 00:00:00 2001 From: David Abbasi Perez Date: Tue, 7 Jul 2026 18:14:56 +0200 Subject: [PATCH 05/15] =?UTF-8?q?feat(state):=20run-state=20layer=20?= =?UTF-8?q?=E2=80=94=20per-run=20events.jsonl=20+=20lazy=20SQLite=20index,?= =?UTF-8?q?=20traincraft=20runs/status=20commands?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - stages emit start/done/skipped/failed events (one small events.jsonl per run, appended by whichever process runs the stage; safe on Lustre because stage jobs are dependency-chained and appends need no locking) - RunIndex: disposable SQLite cache (/index.db) refreshed lazily by the CLI on the login node only; delete-safe, rebuilt from event logs - traincraft runs [outdir] lists all runs; traincraft status shows per-stage state with live labeling progress read from receipts.jsonl - run_status/RunIndex exported in the public API (the base for the MCP/FastAPI service and the workbench) Co-Authored-By: Claude Fable 5 Claude-Session: https://claude.ai/code/session_01V6f4Z4uLdysBeehYfbQ56k --- ROADMAP.md | 12 ++ docs/reference/api.md | 16 ++ docs/reference/cli.md | 49 ++++++ skills/traincraft/SKILL.md | 13 +- src/traincraft/__init__.py | 3 + src/traincraft/cli.py | 56 ++++++ src/traincraft/orchestration/local.py | 4 + src/traincraft/orchestration/slurm.py | 7 + src/traincraft/orchestration/stages.py | 66 ++++++++ src/traincraft/state.py | 225 +++++++++++++++++++++++++ tests/test_state.py | 164 ++++++++++++++++++ 11 files changed, 613 insertions(+), 2 deletions(-) create mode 100644 src/traincraft/state.py create mode 100644 tests/test_state.py diff --git a/ROADMAP.md b/ROADMAP.md index c55a067..54b3e32 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -262,10 +262,22 @@ Acceptance **Goal:** parallelism without touching the science. +### ✅ Run-state layer *(done)* + +- `state.py` — one append-only `events.jsonl` per run (source of truth; safe on + Lustre, no per-frame files) + a disposable SQLite index (`/index.db`) + refreshed lazily by the CLI. `traincraft runs` / `traincraft status` expose it; + labeling progress streams live from `receipts.jsonl`. This is the read API the + agent (L1) and the workbench build on. + +### Remaining + Deliverables - `orchestration/` — `local` engine hardened (threadpool for independent jobs); QuACC adapter expressing the AL loop as a DAG with parallel explore/label fan-out. Engine chosen by simplicity after the core is proven. +- Thin FastAPI/MCP service over `state.py` + `run_stage` (submit, list, status, + report retrieval) — the programmatic surface for agents and the web UI. Acceptance - The same AL workflow runs under `local` and the chosen engine with identical diff --git a/docs/reference/api.md b/docs/reference/api.md index f740176..ba6c675 100644 --- a/docs/reference/api.md +++ b/docs/reference/api.md @@ -141,3 +141,19 @@ frames = tc.read_frames("dataset.extxyz") ::: traincraft.validation.validate.load_reference_frames ::: traincraft.validation.validate.resolve_calculator + +--- + +## Run state + +Event logs + run index (see the [CLI's `runs`/`status`](cli.md#traincraft-runs) +for the command-line view). One `events.jsonl` per run is the source of truth; +the SQLite index is a disposable cache. + +::: traincraft.state.run_status + +::: traincraft.state.RunIndex + +::: traincraft.state.log_event + +::: traincraft.state.read_events diff --git a/docs/reference/cli.md b/docs/reference/cli.md index a677880..409f437 100644 --- a/docs/reference/cli.md +++ b/docs/reference/cli.md @@ -123,6 +123,55 @@ The GPU stages (`sample`, `train`, `validate`) run in `traincraft-mlip.sif` with --- +## `traincraft runs` + +List every run under an output directory with its current status. + +```bash +traincraft runs [OUTDIR] # default: runs/ +``` + +``` +RUN STATUS LAST STAGE UPDATED ENGINE +cnt_water_600K running label 2026-07-07T15:58:11+00:00 slurm +validate_model completed validate 2026-07-07T16:11:02+00:00 local +seed_run failed sample 2026-07-06T09:12:40+00:00 local +``` + +Backed by a SQLite index (`/index.db`), refreshed lazily from each run's +`events.jsonl` — only logs that changed since the last look are re-read, so this +stays fast with thousands of runs. The index is a **disposable cache**: deleting +`index.db` is always safe (it is rebuilt on the next call), and compute jobs +never write to it — on HPC they only append to their own run's event log, which +is why the whole scheme is safe on Lustre/NFS. + +--- + +## `traincraft status` + +Per-stage status of a single run, read from its `events.jsonl`. + +```bash +traincraft status RUN_DIR # e.g. traincraft status runs/cnt_water_600K +``` + +``` +run: cnt_water_600K [running] engine=slurm + geometry done 1 frames 0.4s + sample done 2000 frames 841.2s + select done 400 frames 12.1s + label running 231 done / 4 failed so far + validate pending +``` + +States per stage: `pending` (not reached), `running`, `done`, `cached` (skipped — +artifact up to date), `failed` (with the error message). While the `label` stage +runs, live frame counts are read from `labeled_dft/receipts.jsonl`. Every run +directory carries its own state — no daemon or database is required to ask where +a run is, from any login node. + +--- + ## `traincraft validate` Validate a config file without running anything. diff --git a/skills/traincraft/SKILL.md b/skills/traincraft/SKILL.md index 7eff2dc..dacc1f8 100644 --- a/skills/traincraft/SKILL.md +++ b/skills/traincraft/SKILL.md @@ -65,7 +65,10 @@ dependencies are on the path. `traincraft validate ` and fix every error *before* running. 4. **Run.** `pixi run -e traincraft run `. Confirm with the user before launching anything long (MD, MACE training, Slurm submission). -5. **Review.** Read the outputs under `runs//` (see *Outputs* below). +5. **Review.** Check `traincraft status runs/` (per-stage state, frame + counts, failures, live labeling progress) and read the outputs under + `runs//` (see *Outputs* below). `traincraft runs [outdir]` lists all + runs with their status. 6. **Show the geometry.** Offer to render it (see *Visualising*, below) — the user is usually on a headless VM. @@ -127,7 +130,11 @@ Map the user's words to config keys (run `traincraft plugins` for the live list) - `selected/selected.extxyz` — what survived the selection funnel. - `labeled_dft/labeled.extxyz` (+ `manifest.json`) — DFT-labeled frames. The manifest records `n_attempted`/`n_failed`/`n_reused` and per-frame errors; - failed frames leave their input quarantined in `frame_XXXX/input.extxyz`. + `receipts.jsonl` has one line per attempt (live progress), failed inputs are + quarantined in `failed.extxyz` with the DFT scratch snapshotted to + `failed/frame_N/`. All bookkeeping is append-only files — no dir per frame. +- `events.jsonl` — the run's state log (one line per stage start/done/failure). + Prefer `traincraft status ` over parsing logs to see where a run is. - `dataset.extxyz` — the assembled dataset at the run root. - `model/.model` (+ `manifest.json`, `valid.xyz` holdout) — a trained/fine-tuned MACE model. @@ -158,4 +165,6 @@ traincraft validate # validate + show resolved stages pixi run -e traincraft run # run the pipeline pixi run -e traincraft stage # one stage standalone # (geometry|sample|select|label|dataset|train|validate) +traincraft runs [outdir] # list all runs + status (default outdir: runs/) +traincraft status # per-stage status of one run (live label progress) ``` diff --git a/src/traincraft/__init__.py b/src/traincraft/__init__.py index 6a33e3e..aba41e4 100644 --- a/src/traincraft/__init__.py +++ b/src/traincraft/__init__.py @@ -25,6 +25,7 @@ from .orchestration import run_pipeline from .sampling import run_sampling from .selection import run_funnel +from .state import RunIndex, run_status from .training import run_training from .validation import ValidationResult, run_validation @@ -34,6 +35,7 @@ "Dataset", "Provenance", "Result", + "RunIndex", "Structure", "TrainCraftConfig", "ValidationResult", @@ -51,6 +53,7 @@ "run_funnel", "run_pipeline", "run_sampling", + "run_status", "run_training", "run_validation", "write_frames", diff --git a/src/traincraft/cli.py b/src/traincraft/cli.py index a8e43e0..bca4394 100644 --- a/src/traincraft/cli.py +++ b/src/traincraft/cli.py @@ -10,6 +10,7 @@ from .config import dump_starter_config, load_config from .core import available from .orchestration import STAGE_ORDER, run_pipeline, run_stage, submit_slurm +from .state import RunIndex, run_status app = typer.Typer( add_completion=False, @@ -115,6 +116,61 @@ def new(path: Path = typer.Argument(...)) -> None: typer.echo(f"wrote starter config: {path}") +@app.command() +def runs(outdir: Path = typer.Argument("runs", help="runs root (the [run].outdir)")) -> None: + """List all runs under OUTDIR with their current status. + + Backed by the SQLite index (/index.db), refreshed lazily from each + run's events.jsonl. The index is a cache: deleting it is always safe. + """ + if not outdir.is_dir(): + typer.echo(f"no such directory: {outdir}") + raise typer.Exit(code=1) + index = RunIndex(outdir) + index.refresh() + entries = index.runs() + if not entries: + typer.echo(f"no runs found under {outdir}") + return + typer.echo(f"{'RUN':<24} {'STATUS':<10} {'LAST STAGE':<12} {'UPDATED':<20} ENGINE") + for st in entries: + typer.echo( + f"{st['name']:<24} {st['status']:<10} {st['last_stage'] or '-':<12} " + f"{st['updated'] or '-':<20} {st['engine'] or '-'}" + ) + + +@app.command() +def status(run_dir: Path = typer.Argument(..., help="a run directory (e.g. runs/)")) -> None: + """Per-stage status of one run, read from its events.jsonl.""" + st = run_status(run_dir) + if st["status"] == "empty": + typer.echo(f"no run state recorded in {run_dir} (no events.jsonl)") + raise typer.Exit(code=1) + typer.echo(f"run: {st['name']} [{st['status']}] engine={st['engine'] or '-'}") + names = st["planned"] or [n for n in STAGE_ORDER if n in st["stages"]] + for name in names: + stage = st["stages"].get(name) + if stage is None: + typer.echo(f" {name:<10} pending") + continue + parts = [stage["state"]] + if "n_frames" in stage: + parts.append(f"{stage['n_frames']} frames") + if stage.get("n_failed"): + parts.append(f"{stage['n_failed']} failed") + if "passed" in stage: + parts.append({True: "passed", False: "FAILED", None: "no thresholds"}[stage["passed"]]) + if "wall_seconds" in stage: + parts.append(f"{stage['wall_seconds']}s") + if "progress" in stage: + p = stage["progress"] + parts.append(f"{p['n_done']} done / {p['n_failed']} failed so far") + if "error" in stage: + parts.append(stage["error"]) + typer.echo(f" {name:<10} {' '.join(parts)}") + + @app.command() def plugins() -> None: """List registered plugins by kind.""" diff --git a/src/traincraft/orchestration/local.py b/src/traincraft/orchestration/local.py index f8538b5..70307ab 100644 --- a/src/traincraft/orchestration/local.py +++ b/src/traincraft/orchestration/local.py @@ -14,8 +14,10 @@ from ..config import TrainCraftConfig from ..datasets import Dataset +from ..state import log_event from ..validation import REPORT_NAME from .stages import ( + enabled_stages, stage_dataset, stage_geometry, stage_label, @@ -36,6 +38,7 @@ def run_pipeline(config: TrainCraftConfig, *, force: bool = False) -> dict: ws = workspace_for(config) if config.run.seed is not None: np.random.seed(config.run.seed) + log_event(ws.root, "run", "start", engine="local", stages=enabled_stages(config)) stage_geometry(config, ws, force=force) candidates = stage_sample(config, ws, force=force) @@ -62,4 +65,5 @@ def run_pipeline(config: TrainCraftConfig, *, force: bool = False) -> dict: report_path = ws.root / "validation" / REPORT_NAME summary["quality_report"] = str(report_path) summary["validation_passed"] = json.loads(report_path.read_text())["passed"] + log_event(ws.root, "run", "done", summary=summary) return summary diff --git a/src/traincraft/orchestration/slurm.py b/src/traincraft/orchestration/slurm.py index 0b9f62a..aec70ca 100644 --- a/src/traincraft/orchestration/slurm.py +++ b/src/traincraft/orchestration/slurm.py @@ -41,6 +41,7 @@ from ..config import TrainCraftConfig from ..core import Workspace +from ..state import log_event from .stages import enabled_stages, workspace_for logger = logging.getLogger(__name__) @@ -213,4 +214,10 @@ def submit( raise RuntimeError(f"could not parse job id from sbatch output: {out.stdout!r}") job.job_id = prev_id = match.group(1) logger.info("submitted %s as job %s (after %s)", job.stage, job.job_id, job.depends_on) + log_event( + ws.root, "run", "start", + engine="slurm", + stages=[j.stage for j in jobs], + jobs={j.stage: j.job_id for j in jobs}, + ) return jobs diff --git a/src/traincraft/orchestration/stages.py b/src/traincraft/orchestration/stages.py index 02d4e1d..007c499 100644 --- a/src/traincraft/orchestration/stages.py +++ b/src/traincraft/orchestration/stages.py @@ -27,9 +27,11 @@ from __future__ import annotations +import functools import hashlib import json import logging +import time from pathlib import Path import numpy as np @@ -42,6 +44,7 @@ from ..labeling import label_frames from ..sampling import run_sampling from ..selection import run_funnel +from ..state import log_event from ..training import run_training from ..validation import REPORT_NAME, load_reference_frames, resolve_calculator, run_validation @@ -175,21 +178,47 @@ def _fresh(artifact: Path, key: str) -> bool: # --- individual stages ------------------------------------------------------ +def _emit(ws: Workspace, stage: str, event: str, **data) -> None: + log_event(ws.root, stage, event, **data) + + +def _instrumented(fn): + """Emit a ``failed`` event (then re-raise) when a stage dies.""" + stage = fn.__name__.removeprefix("stage_") + + @functools.wraps(fn) + def wrapper(config, ws, force=False): + try: + return fn(config, ws, force=force) + except Exception as exc: + _emit(ws, stage, "failed", error=f"{type(exc).__name__}: {exc}") + raise + + return wrapper + + +@_instrumented def stage_geometry(config, ws, force=False): out = _artifact_path(ws, "geometry") key = _stage_key(config, ws, "geometry") if not force and _fresh(out, key): logger.info("geometry: up to date, skipping (%s)", out) + _emit(ws, "geometry", "skipped", artifact=str(out)) return read_frames(out) if config.geometry is None: raise ValueError("config has no [geometry] section: nothing to build") + _emit(ws, "geometry", "start") + t0 = time.perf_counter() structure = build_geometry(config.geometry) ws.subdir("structures") write_frames(out, [structure]) _write_key(out, key) + _emit(ws, "geometry", "done", n_frames=1, + wall_seconds=round(time.perf_counter() - t0, 2), artifact=str(out)) return [structure] +@_instrumented def stage_sample(config, ws, force=False): if config.sampling is None: return _latest_upstream(ws, "sample") @@ -197,18 +226,24 @@ def stage_sample(config, ws, force=False): key = _stage_key(config, ws, "sample") if not force and _fresh(out, key): logger.info("sample: up to date, skipping (%s)", out) + _emit(ws, "sample", "skipped", artifact=str(out)) return read_frames(out) if config.calculator is None: raise ValueError("[sampling] needs a [calculator]") structure = _latest_upstream(ws, "sample")[0] calc = make_calculator(config.calculator) job = ws.job("candidates") + _emit(ws, "sample", "start") + t0 = time.perf_counter() candidates = run_sampling(structure, calc, job, config.sampling) write_frames(out, candidates) _write_key(out, key) + _emit(ws, "sample", "done", n_frames=len(candidates), + wall_seconds=round(time.perf_counter() - t0, 2), artifact=str(out)) return candidates +@_instrumented def stage_select(config, ws, force=False): if config.selection is None: return _latest_upstream(ws, "select") @@ -216,14 +251,20 @@ def stage_select(config, ws, force=False): key = _stage_key(config, ws, "select") if not force and _fresh(out, key): logger.info("select: up to date, skipping (%s)", out) + _emit(ws, "select", "skipped", artifact=str(out)) return read_frames(out) + _emit(ws, "select", "start") + t0 = time.perf_counter() selected = run_funnel(_latest_upstream(ws, "select"), config.selection) ws.subdir("selected") write_frames(out, selected) _write_key(out, key) + _emit(ws, "select", "done", n_frames=len(selected), + wall_seconds=round(time.perf_counter() - t0, 2), artifact=str(out)) return selected +@_instrumented def stage_label(config, ws, force=False): if config.labeling is None: return _latest_upstream(ws, "label") @@ -231,9 +272,12 @@ def stage_label(config, ws, force=False): key = _stage_key(config, ws, "label") if not force and _fresh(out, key): logger.info("label: up to date, skipping (%s)", out) + _emit(ws, "label", "skipped", artifact=str(out)) return read_frames(out) job = ws.job("labeled_dft") frames = _latest_upstream(ws, "label") + _emit(ws, "label", "start", n_in=len(frames)) + t0 = time.perf_counter() labeled = label_frames( frames, config.labeling.calculator, @@ -242,9 +286,14 @@ def stage_label(config, ws, force=False): ) write_frames(out, labeled) _write_key(out, key) + manifest = json.loads((job.dir / "manifest.json").read_text()) + _emit(ws, "label", "done", n_frames=len(labeled), n_failed=manifest["n_failed"], + n_reused=manifest["n_reused"], + wall_seconds=round(time.perf_counter() - t0, 2), artifact=str(out)) return labeled +@_instrumented def stage_dataset(config, ws, force=False): frames = _latest_upstream(ws, "dataset") if config.dataset is None: @@ -253,14 +302,20 @@ def stage_dataset(config, ws, force=False): key = _stage_key(config, ws, "dataset") if not force and _fresh(ds.path, key): logger.info("dataset: up to date, skipping (%s)", ds.path) + _emit(ws, "dataset", "skipped", artifact=str(ds.path)) return frames + _emit(ws, "dataset", "start") + t0 = time.perf_counter() ds.append(frames) ds.write() _write_key(ds.path, key) logger.info("dataset written: %s (%d frames)", ds.path, len(ds)) + _emit(ws, "dataset", "done", n_frames=len(ds), + wall_seconds=round(time.perf_counter() - t0, 2), artifact=str(ds.path)) return frames +@_instrumented def stage_train(config, ws, force=False): if config.training is None: return _latest_upstream(ws, "train") @@ -269,14 +324,19 @@ def stage_train(config, ws, force=False): key = _stage_key(config, ws, "train") if not force and _fresh(manifest, key): logger.info("train: up to date, skipping (%s)", manifest) + _emit(ws, "train", "skipped", artifact=str(manifest)) return _training_frames(config, ws) frames = _training_frames(config, ws) + _emit(ws, "train", "start", n_in=len(frames)) + t0 = time.perf_counter() result = run_training(frames, config.training, job) _write_key(manifest, key) logger.info( "trained '%s' on %d frames (model: %s)", config.training.name, result.n_train, result.model_path, ) + _emit(ws, "train", "done", n_frames=result.n_train, + wall_seconds=round(time.perf_counter() - t0, 2), artifact=str(result.model_path)) return frames @@ -289,6 +349,7 @@ def _training_frames(config, ws) -> list: return _latest_upstream(ws, "train") +@_instrumented def stage_validate(config, ws, force=False): if config.validation is None: return _latest_upstream(ws, "validate") @@ -296,15 +357,20 @@ def stage_validate(config, ws, force=False): key = _stage_key(config, ws, "validate") if not force and _fresh(out, key): logger.info("validate: up to date, skipping (%s)", out) + _emit(ws, "validate", "skipped", artifact=str(out)) return _validation_frames(config, ws) frames = _validation_frames(config, ws) calc_cfg = resolve_calculator(config.validation, ws.root / "model" / "manifest.json") + _emit(ws, "validate", "start", n_in=len(frames)) + t0 = time.perf_counter() result = run_validation(frames, calc_cfg, config.validation, out_dir=ws.root / "validation") _write_key(out, key) verdict = {True: "passed", False: "FAILED", None: "no thresholds set"}[result.passed] logger.info( "validated %d frames (%s): %s", result.n_frames, verdict, result.report_path ) + _emit(ws, "validate", "done", n_frames=result.n_frames, passed=result.passed, + wall_seconds=round(time.perf_counter() - t0, 2), artifact=str(out)) return frames diff --git a/src/traincraft/state.py b/src/traincraft/state.py new file mode 100644 index 0000000..8a453c6 --- /dev/null +++ b/src/traincraft/state.py @@ -0,0 +1,225 @@ +"""Run state: append-only event logs + a disposable SQLite index. + +Every stage appends one JSON line to ``/events.jsonl`` when it starts, +finishes, is skipped (cache hit), or fails; the runner adds run-level events +(engine, planned stages). That file is the **source of truth** for a run's +state: one small file per run whose size scales with the number of *stages*, +never with the number of frames the run labels. + +Why this split (and not SQLite everywhere): on HPC the stage processes run on +compute nodes against Lustre/NFS, where SQLite's POSIX-lock-based concurrency +is exactly what network filesystems get wrong (silent corruption). Appends to +one file per run need no locking — and stage jobs are dependency-chained, so +there is never more than one writer at a time anyway. + +The cross-run index (``/index.db``) is a **cache**: SQLite, written +only by the CLI/service on the login node (single writer), refreshed lazily +from whichever event logs changed since the last look. Deleting it is always +safe — the next ``traincraft runs`` rebuilds it from the event logs. +""" + +from __future__ import annotations + +import json +import logging +import sqlite3 +from datetime import datetime, timezone +from pathlib import Path + +logger = logging.getLogger(__name__) + +EVENTS_NAME = "events.jsonl" +INDEX_NAME = "index.db" + +_STAGE_STATE = {"start": "running", "done": "done", "skipped": "cached", "failed": "failed"} + + +def log_event(run_dir: str | Path, stage: str, event: str, **data) -> None: + """Append one event record to the run's log (best-effort: never raises OSError).""" + record = { + "ts": datetime.now(timezone.utc).isoformat(timespec="seconds"), + "stage": stage, + "event": event, + **data, + } + try: + run_dir = Path(run_dir) + run_dir.mkdir(parents=True, exist_ok=True) + with (run_dir / EVENTS_NAME).open("a") as fh: + fh.write(json.dumps(record, default=str) + "\n") + except OSError: # state logging must never kill the science + logger.warning("could not append to %s", run_dir / EVENTS_NAME, exc_info=True) + + +def read_events(run_dir: str | Path) -> list[dict]: + """All events of a run, oldest first (empty if the run has no log).""" + path = Path(run_dir) / EVENTS_NAME + if not path.exists(): + return [] + events = [] + for line in path.read_text().splitlines(): + line = line.strip() + if not line: + continue + try: + events.append(json.loads(line)) + except json.JSONDecodeError: # torn write at a crash: skip the line + logger.debug("skipping malformed event line in %s", path) + return events + + +def _label_progress(run_dir: Path, since_ts: str | None) -> dict | None: + """Live per-frame counts for a running label stage, from receipts.jsonl.""" + from .labeling import RECEIPTS_NAME # local import: avoid cycle at module load + + receipts = run_dir / "labeled_dft" / RECEIPTS_NAME + if not receipts.exists(): + return None + n_ok = n_failed = 0 + for line in receipts.read_text().splitlines(): + try: + rec = json.loads(line) + except json.JSONDecodeError: + continue + if since_ts and rec.get("ts", "") < since_ts: + continue # receipts from an earlier attempt + if rec.get("status") == "ok": + n_ok += 1 + elif rec.get("status") == "failed": + n_failed += 1 + return {"n_done": n_ok, "n_failed": n_failed} + + +def run_status(run_dir: str | Path) -> dict: + """Fold a run's event log into its current status. + + Returns ``{"name", "status", "engine", "planned", "stages": {stage: {...}}, + "started", "updated"}`` where ``status`` is one of ``empty | running | + failed | completed | partial`` (partial: some stages done, plan unknown or + unfinished, nothing currently running). + """ + run_dir = Path(run_dir) + events = read_events(run_dir) + stages: dict[str, dict] = {} + engine = None + planned: list[str] | None = None + started = updated = None + + for e in events: + ts = e.get("ts") + started = started or ts + updated = ts or updated + name, ev = e.get("stage"), e.get("event") + data = {k: v for k, v in e.items() if k not in ("stage", "event", "ts")} + if name == "run": + engine = data.get("engine", engine) + planned = data.get("stages", planned) + continue + if ev == "start": + stages[name] = {"state": "running", "started": ts, **data} + elif ev in _STAGE_STATE: + st = stages.setdefault(name, {}) + st.update(data) + st["state"] = _STAGE_STATE[ev] + + label = stages.get("label") + if label is not None and label["state"] == "running": + progress = _label_progress(run_dir, label.get("started")) + if progress is not None: + label["progress"] = progress + + states = [st["state"] for st in stages.values()] + if not stages: + status = "empty" + elif "failed" in states: + status = "failed" + elif "running" in states: + status = "running" + elif planned and all( + stages.get(p, {}).get("state") in ("done", "cached") for p in planned + ): + status = "completed" + elif planned: + status = "partial" + else: # no plan recorded (standalone stage runs): all seen stages finished + status = "partial" + + last_stage = next(reversed(stages), None) + return { + "name": run_dir.name, + "dir": str(run_dir), + "status": status, + "engine": engine, + "planned": planned, + "stages": stages, + "last_stage": last_stage, + "started": started, + "updated": updated, + } + + +class RunIndex: + """SQLite index over every run below ``outdir`` — a disposable cache. + + ``refresh()`` re-derives rows only for runs whose ``events.jsonl`` changed + since the last refresh, and drops rows whose run directories vanished. + Only ever open this on the submit/login side (single writer); compute jobs + write event logs, never the index. + """ + + def __init__(self, outdir: str | Path): + self.outdir = Path(outdir) + self.path = self.outdir / INDEX_NAME + + def _connect(self) -> sqlite3.Connection: + con = sqlite3.connect(self.path) + con.execute( + """CREATE TABLE IF NOT EXISTS runs ( + dir TEXT PRIMARY KEY, name TEXT, status TEXT, last_stage TEXT, + engine TEXT, started TEXT, updated TEXT, + events_mtime REAL, detail TEXT)""" + ) + return con + + def refresh(self) -> int: + """Sync the index with the event logs on disk; return #rows updated.""" + con = self._connect() + try: + known = dict(con.execute("SELECT dir, events_mtime FROM runs")) + seen, updated = set(), 0 + for events in sorted(self.outdir.glob(f"*/{EVENTS_NAME}")): + run_dir = events.parent + seen.add(str(run_dir)) + mtime = events.stat().st_mtime + if known.get(str(run_dir)) == mtime: + continue + st = run_status(run_dir) + con.execute( + "REPLACE INTO runs VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)", + ( + str(run_dir), st["name"], st["status"], st["last_stage"], + st["engine"], st["started"], st["updated"], + mtime, json.dumps(st), + ), + ) + updated += 1 + gone = set(known) - seen + if gone: + con.executemany( + "DELETE FROM runs WHERE dir = ?", [(d,) for d in gone] + ) + con.commit() + return updated + finally: + con.close() + + def runs(self) -> list[dict]: + """All indexed runs, most recently updated first.""" + con = self._connect() + try: + rows = con.execute( + "SELECT detail FROM runs ORDER BY updated DESC, name" + ).fetchall() + return [json.loads(detail) for (detail,) in rows] + finally: + con.close() diff --git a/tests/test_state.py b/tests/test_state.py new file mode 100644 index 0000000..145f0f6 --- /dev/null +++ b/tests/test_state.py @@ -0,0 +1,164 @@ +"""Run-state layer: event logs, status folding, and the SQLite run index.""" + +from __future__ import annotations + +import json + +import pytest + +from traincraft import RunIndex, run_pipeline, run_status +from traincraft.config.models import ( + CrystalBuilder, + EmtCalc, + GeometryConfig, + LabelingConfig, + MdSampling, + RunConfig, + SelectionConfig, + TrainCraftConfig, +) +from traincraft.state import EVENTS_NAME, log_event, read_events + + +def _config(tmp_path, name="evrun", **overrides): + kwargs = dict( + run=RunConfig(name=name, outdir=str(tmp_path), seed=1), + geometry=GeometryConfig( + builder=CrystalBuilder( + name="Cu", crystalstructure="fcc", a=3.6, cubic=True, supercell=(2, 2, 2) + ) + ), + calculator=EmtCalc(), + sampling=MdSampling(temperature=300.0, steps=30, interval=10), + selection=SelectionConfig(budget=2), + labeling=LabelingConfig(calculator=EmtCalc()), + ) + kwargs.update(overrides) + return TrainCraftConfig(**kwargs) + + +def test_log_and_read_events_roundtrip(tmp_path): + log_event(tmp_path, "geometry", "start") + log_event(tmp_path, "geometry", "done", n_frames=1, wall_seconds=0.1) + events = read_events(tmp_path) + assert [e["event"] for e in events] == ["start", "done"] + assert events[1]["n_frames"] == 1 + assert all("ts" in e for e in events) + + +def test_read_events_skips_torn_lines(tmp_path): + log_event(tmp_path, "sample", "start") + with (tmp_path / EVENTS_NAME).open("a") as fh: + fh.write('{"stage": "sample", "ev') # crash mid-write + assert len(read_events(tmp_path)) == 1 + + +def test_run_status_empty(tmp_path): + assert run_status(tmp_path)["status"] == "empty" + + +def test_run_status_folds_stage_lifecycle(tmp_path): + log_event(tmp_path, "run", "start", engine="local", stages=["geometry", "sample"]) + log_event(tmp_path, "geometry", "start") + log_event(tmp_path, "geometry", "done", n_frames=1, wall_seconds=0.1) + log_event(tmp_path, "sample", "start") + + st = run_status(tmp_path) + assert st["status"] == "running" + assert st["engine"] == "local" + assert st["stages"]["geometry"]["state"] == "done" + assert st["stages"]["sample"]["state"] == "running" + assert st["last_stage"] == "sample" + + log_event(tmp_path, "sample", "done", n_frames=5, wall_seconds=0.2) + assert run_status(tmp_path)["status"] == "completed" + + +def test_run_status_failed_and_recovered(tmp_path): + log_event(tmp_path, "run", "start", engine="local", stages=["geometry"]) + log_event(tmp_path, "geometry", "start") + log_event(tmp_path, "geometry", "failed", error="ValueError: boom") + st = run_status(tmp_path) + assert st["status"] == "failed" + assert "boom" in st["stages"]["geometry"]["error"] + + # a successful rerun supersedes the failure + log_event(tmp_path, "geometry", "start") + log_event(tmp_path, "geometry", "done", n_frames=1) + assert run_status(tmp_path)["status"] == "completed" + + +def test_run_status_label_progress_from_receipts(tmp_path): + log_event(tmp_path, "run", "start", engine="slurm", stages=["label"]) + log_event(tmp_path, "label", "start", n_in=100) + receipts = tmp_path / "labeled_dft" + receipts.mkdir() + lines = [ + {"ts": "2099-01-01T00:00:00+00:00", "i": i, "status": "ok" if i else "failed"} + for i in range(4) + ] + (receipts / "receipts.jsonl").write_text("\n".join(json.dumps(x) for x in lines) + "\n") + + st = run_status(tmp_path) + assert st["stages"]["label"]["progress"] == {"n_done": 3, "n_failed": 1} + + +def test_pipeline_emits_events_and_completes(tmp_path): + cfg = _config(tmp_path) + run_pipeline(cfg) + run_dir = tmp_path / "evrun" + assert (run_dir / EVENTS_NAME).exists() + + st = run_status(run_dir) + assert st["status"] == "completed" + assert st["planned"] == ["geometry", "sample", "select", "label"] + assert all(st["stages"][s]["state"] == "done" for s in st["planned"]) + assert st["stages"]["label"]["n_failed"] == 0 + + # rerun: everything cached, still reads as completed + run_pipeline(cfg) + st = run_status(run_dir) + assert st["status"] == "completed" + assert all(st["stages"][s]["state"] == "cached" for s in st["planned"]) + + +def test_pipeline_failure_recorded(tmp_path, monkeypatch): + def _explode(*a, **k): + raise RuntimeError("no calculator today") + + monkeypatch.setattr("traincraft.orchestration.stages.run_sampling", _explode) + cfg = _config(tmp_path, name="evfail") + with pytest.raises(RuntimeError, match="no calculator today"): + run_pipeline(cfg) + + st = run_status(tmp_path / "evfail") + assert st["status"] == "failed" + assert st["stages"]["sample"]["state"] == "failed" + assert "no calculator today" in st["stages"]["sample"]["error"] + + +def test_run_index_refresh_and_list(tmp_path): + run_pipeline(_config(tmp_path, name="run_a")) + run_pipeline(_config(tmp_path, name="run_b")) + + index = RunIndex(tmp_path) + assert index.refresh() == 2 + assert index.refresh() == 0 # nothing changed since + names = {st["name"] for st in index.runs()} + assert names == {"run_a", "run_b"} + assert all(st["status"] == "completed" for st in index.runs()) + + # index is a disposable cache: delete and it rebuilds + index.path.unlink() + assert RunIndex(tmp_path).refresh() == 2 + + +def test_run_index_drops_vanished_runs(tmp_path): + import shutil + + run_pipeline(_config(tmp_path, name="run_a")) + index = RunIndex(tmp_path) + index.refresh() + shutil.rmtree(tmp_path / "run_a") + index.refresh() + assert index.runs() == [] From be9e8cb267799b09a4b864474157ef796dc609c3 Mon Sep 17 00:00:00 2001 From: David Abbasi Perez Date: Tue, 7 Jul 2026 19:27:54 +0200 Subject: [PATCH 06/15] feat(service): HTTP (FastAPI) + MCP service over the run-state layer MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - service/core.py: shared, dependency-free ops (list/status/events/report/ manifest, TOML validation, submission — Slurm or detached local process) - traincraft serve: localhost FastAPI app with OpenAPI docs at /docs - traincraft mcp: the same six operations as MCP tools on stdio, with working rules (validate before submit, judge models only by the quality report) encoded in the tool docstrings - optional deps behind 'pixi install -e service'; new how-to page + CLI/API reference; roadmap updated Co-Authored-By: Claude Fable 5 Claude-Session: https://claude.ai/code/session_01V6f4Z4uLdysBeehYfbQ56k --- ROADMAP.md | 9 +- docs/how-to/agent-service.md | 84 +++ docs/how-to/index.md | 1 + docs/reference/api.md | 23 + docs/reference/cli.md | 28 + mkdocs.yml | 1 + pixi.lock | 886 ++++++++++++++++++++++++++- pyproject.toml | 9 + skills/traincraft/SKILL.md | 4 + src/traincraft/cli.py | 37 ++ src/traincraft/service/__init__.py | 12 + src/traincraft/service/app.py | 91 +++ src/traincraft/service/core.py | 137 +++++ src/traincraft/service/mcp_server.py | 82 +++ tests/test_service.py | 195 ++++++ 15 files changed, 1596 insertions(+), 3 deletions(-) create mode 100644 docs/how-to/agent-service.md create mode 100644 src/traincraft/service/__init__.py create mode 100644 src/traincraft/service/app.py create mode 100644 src/traincraft/service/core.py create mode 100644 src/traincraft/service/mcp_server.py create mode 100644 tests/test_service.py diff --git a/ROADMAP.md b/ROADMAP.md index 54b3e32..b415bc2 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -270,14 +270,19 @@ Acceptance labeling progress streams live from `receipts.jsonl`. This is the read API the agent (L1) and the workbench build on. +### ✅ Service layer (HTTP + MCP) *(done)* + +- `service/` — shared ops in `core.py`; `traincraft serve` (FastAPI: runs, + status, events, quality reports, manifests, config validation, submission) + and `traincraft mcp` (the same six operations as agent tools over stdio). + Optional deps behind `pixi install -e service`. + ### Remaining Deliverables - `orchestration/` — `local` engine hardened (threadpool for independent jobs); QuACC adapter expressing the AL loop as a DAG with parallel explore/label fan-out. Engine chosen by simplicity after the core is proven. -- Thin FastAPI/MCP service over `state.py` + `run_stage` (submit, list, status, - report retrieval) — the programmatic surface for agents and the web UI. Acceptance - The same AL workflow runs under `local` and the chosen engine with identical diff --git a/docs/how-to/agent-service.md b/docs/how-to/agent-service.md new file mode 100644 index 0000000..dc710cc --- /dev/null +++ b/docs/how-to/agent-service.md @@ -0,0 +1,84 @@ +# Serve Runs to Agents & UIs (HTTP + MCP) + +TrainCraft ships a thin **service layer** that exposes run state, quality +reports and pipeline submission over two transports — a FastAPI **HTTP API** +(for dashboards/scripts) and an **MCP server** (for AI agents). Both are +wrappers over the same functions (`traincraft.service.core`), so they expose +exactly the same capabilities. Nothing else is needed beside the runs +directory: state comes from each run's `events.jsonl` and stage manifests. + +```bash +pixi install -e service # fastapi + uvicorn + mcp (optional extras) +``` + +--- + +## HTTP API + +```bash +pixi run -e service traincraft serve runs/ # http://127.0.0.1:8137 +``` + +Interactive OpenAPI docs at `http://127.0.0.1:8137/docs`. + +| Endpoint | Returns | +|---|---| +| `GET /runs` | all runs with status/last stage/engine (lazy-refreshed index) | +| `GET /runs/{name}` | per-stage status incl. live labeling progress | +| `GET /runs/{name}/events` | the raw event log | +| `GET /runs/{name}/report` | `quality_report.json` (metrics, checks, passed) | +| `GET /runs/{name}/manifest/{stage}` | a stage manifest (`label`, `train`) | +| `POST /config/validate` | validate TOML text: `{"toml": "..."}` → `{valid, name, stages, errors}` | +| `POST /runs` | start a pipeline: `{"config_path": "...", "force": false}` | + +`POST /runs` returns immediately: Slurm configs are submitted as +dependency-chained jobs; anything else runs as a detached local process +(output to `/local.log`). Track progress with `GET /runs/{name}`. + +!!! warning "Localhost tool — no auth" + The service exposes results and can start pipelines from server-side + config paths. It binds to `127.0.0.1` by default; keep it there (or put a + real authenticating gateway in front). Never expose it raw to a network. + +--- + +## MCP server (agents) + +The same operations as MCP tools, over stdio: + +```bash +# register with Claude Code: +claude mcp add traincraft -- pixi run -e service traincraft mcp /abs/path/to/runs +``` + +| Tool | Purpose | +|---|---| +| `list_runs` | find runs + status | +| `run_status(name)` | per-stage state, counts, errors, live label progress | +| `quality_report(name)` | the validation verdict — read before any model claim | +| `stage_manifest(name, stage)` | level of theory / training command + counts | +| `validate_config(toml_text)` | check a config before submitting | +| `submit_run(config_path, force)` | start a pipeline (confirm cost with the user first) | + +The tool docstrings encode the working rules (validate before submit; judge +models only by their quality report), so any MCP-capable agent inherits them. +For richer agent behaviour (config *authoring*, environment selection, +visualisation), pair the MCP server with the TrainCraft skill +(`skills/traincraft/SKILL.md`), which the agent uses via the CLI. + +--- + +## From Python + +```python +from traincraft.service import core + +core.list_runs("runs") +core.get_run("runs", "my_run") +core.get_report("runs", "my_run") +core.validate_config_text(toml_text) +core.submit_config("my_run.toml") +``` + +`create_app(outdir)` / `create_mcp(outdir)` build the FastAPI app and MCP +server if you want to mount them inside a larger application. diff --git a/docs/how-to/index.md b/docs/how-to/index.md index 1be4100..d6c48e7 100644 --- a/docs/how-to/index.md +++ b/docs/how-to/index.md @@ -11,3 +11,4 @@ background explanations. | [Use Your Own MACE Model](own-mace-model.md) | You have a fine-tuned checkpoint to deploy | | [Manage Datasets](datasets.md) | Merging, filtering, and inspecting extxyz datasets | | [Run on HPC (Slurm + Apptainer)](hpc.md) | Build the containers and dispatch the pipeline on any Slurm cluster | +| [Serve Runs to Agents & UIs (HTTP + MCP)](agent-service.md) | Expose run state/reports/submission to dashboards and AI agents | diff --git a/docs/reference/api.md b/docs/reference/api.md index ba6c675..8e05e48 100644 --- a/docs/reference/api.md +++ b/docs/reference/api.md @@ -157,3 +157,26 @@ the SQLite index is a disposable cache. ::: traincraft.state.log_event ::: traincraft.state.read_events + +--- + +## Service layer + +The HTTP app and MCP server are thin wrappers over `traincraft.service.core` +(see [Serve Runs to Agents & UIs](../how-to/agent-service.md)). + +::: traincraft.service.create_app + +::: traincraft.service.create_mcp + +::: traincraft.service.core.list_runs + +::: traincraft.service.core.get_run + +::: traincraft.service.core.get_report + +::: traincraft.service.core.get_manifest + +::: traincraft.service.core.validate_config_text + +::: traincraft.service.core.submit_config diff --git a/docs/reference/cli.md b/docs/reference/cli.md index 409f437..c666338 100644 --- a/docs/reference/cli.md +++ b/docs/reference/cli.md @@ -172,6 +172,34 @@ a run is, from any login node. --- +## `traincraft serve` + +Serve the HTTP API over a runs directory (needs `pixi install -e service`). + +```bash +traincraft serve [OUTDIR] [--host 127.0.0.1] [--port 8137] +``` + +Endpoints: runs list/status/events, quality reports, stage manifests, config +validation, pipeline submission — OpenAPI docs at `/docs`. **Localhost tool +with no auth**; see [Serve Runs to Agents & UIs](../how-to/agent-service.md). + +--- + +## `traincraft mcp` + +Run the MCP server on stdio — the same operations as agent tools +(`list_runs`, `run_status`, `quality_report`, `stage_manifest`, +`validate_config`, `submit_run`). + +```bash +claude mcp add traincraft -- pixi run -e service traincraft mcp /abs/path/to/runs +``` + +See [Serve Runs to Agents & UIs](../how-to/agent-service.md). + +--- + ## `traincraft validate` Validate a config file without running anything. diff --git a/mkdocs.yml b/mkdocs.yml index fdc5460..7c60f93 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -128,6 +128,7 @@ nav: - Train & Use Your Own MACE Model: how-to/own-mace-model.md - Manage Datasets: how-to/datasets.md - Run on HPC (Slurm + Apptainer): how-to/hpc.md + - Serve Runs to Agents & UIs: how-to/agent-service.md - Reference: - reference/index.md - CLI: reference/cli.md diff --git a/pixi.lock b/pixi.lock index 36fce95..729bc60 100644 --- a/pixi.lock +++ b/pixi.lock @@ -681,6 +681,161 @@ environments: - pypi: https://files.pythonhosted.org/packages/32/d5/f9a850d79b0851d1d4ef6456097579a9005b31fea68726a4ae5f2d82ddd9/threadpoolctl-3.6.0-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/a9/aa/714334aac6e3fe8c4c5382fe7fc9cba9a9727e05b7eb7e37edcee7d11ca4/trainstation-1.2-py3-none-any.whl - pypi: ./ + service: + channels: + - url: https://conda.anaconda.org/conda-forge/ + indexes: + - https://pypi.org/simple + options: + pypi-prerelease-mode: if-necessary-or-explicit + packages: + linux-64: + - conda: https://conda.anaconda.org/conda-forge/linux-64/_openmp_mutex-4.5-20_gnu.conda + - conda: https://conda.anaconda.org/conda-forge/noarch/_python_abi3_support-1.0-hd8ed1ab_2.conda + - conda: https://conda.anaconda.org/conda-forge/noarch/annotated-doc-0.0.4-pyhcf101f3_0.conda + - conda: https://conda.anaconda.org/conda-forge/noarch/annotated-types-0.7.0-pyhd8ed1ab_1.conda + - conda: https://conda.anaconda.org/conda-forge/noarch/ase-3.29.0-pyhd8ed1ab_1.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/ast-serialize-0.6.0-py310hd8a072f_0.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/brotli-1.2.0-hed03a55_1.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/brotli-bin-1.2.0-hb03c661_1.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/bzip2-1.0.8-hda65f42_9.conda + - conda: https://conda.anaconda.org/conda-forge/noarch/ca-certificates-2026.6.17-hbd8a1cb_0.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/cairo-1.18.4-he90730b_1.conda + - conda: https://conda.anaconda.org/conda-forge/noarch/colorama-0.4.6-pyhd8ed1ab_1.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/contourpy-1.3.3-py312h0a2e395_4.conda + - conda: https://conda.anaconda.org/conda-forge/noarch/cpython-3.12.13-py312hd8ed1ab_0.conda + - conda: https://conda.anaconda.org/conda-forge/noarch/cycler-0.12.1-pyhcf101f3_2.conda + - conda: https://conda.anaconda.org/conda-forge/noarch/exceptiongroup-1.3.1-pyhd8ed1ab_0.conda + - conda: https://conda.anaconda.org/conda-forge/noarch/font-ttf-dejavu-sans-mono-2.37-hab24e00_0.tar.bz2 + - conda: https://conda.anaconda.org/conda-forge/noarch/font-ttf-inconsolata-3.000-h77eed37_0.tar.bz2 + - conda: https://conda.anaconda.org/conda-forge/noarch/font-ttf-source-code-pro-2.038-h77eed37_0.tar.bz2 + - conda: https://conda.anaconda.org/conda-forge/noarch/font-ttf-ubuntu-0.83-h77eed37_3.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/fontconfig-2.18.1-h27c8c51_0.conda + - conda: https://conda.anaconda.org/conda-forge/noarch/fonts-conda-ecosystem-1-0.tar.bz2 + - conda: https://conda.anaconda.org/conda-forge/noarch/fonts-conda-forge-1-hc364b38_1.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/fonttools-4.63.0-py312h8a5da7c_0.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/freetype-2.14.3-ha770c72_0.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/fribidi-1.0.16-hb03c661_0.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/graphite2-1.3.15-hecca717_0.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/icu-78.3-h33c6efd_0.conda + - conda: https://conda.anaconda.org/conda-forge/noarch/iniconfig-2.3.0-pyhd8ed1ab_0.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/kiwisolver-1.5.0-py312h0a2e395_0.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/lcms2-2.19.1-h0c24ade_1.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/ld_impl_linux-64-2.45.1-default_hbd61a6d_102.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/lerc-4.1.0-hdb68285_0.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/libblas-3.11.0-8_h4a7cf45_openblas.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/libbrotlicommon-1.2.0-hb03c661_1.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/libbrotlidec-1.2.0-hb03c661_1.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/libbrotlienc-1.2.0-hb03c661_1.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/libcblas-3.11.0-8_h0358290_openblas.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/libdeflate-1.25-h17f619e_0.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/libexpat-2.8.1-hecca717_1.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/libffi-3.5.2-h3435931_0.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/libfreetype-2.14.3-ha770c72_0.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/libfreetype6-2.14.3-h73754d4_0.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/libgcc-15.2.0-he0feb66_19.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/libgcc-ng-15.2.0-h69a702a_19.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/libgfortran-15.2.0-h69a702a_19.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/libgfortran5-15.2.0-h68bc16d_19.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/libglib-2.88.2-h0d30a3d_0.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/libgomp-15.2.0-he0feb66_19.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/libharfbuzz-14.2.1-h17a8019_1.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/libiconv-1.18-h3b78370_2.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/libjpeg-turbo-3.1.4.1-hb03c661_0.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/liblapack-3.11.0-8_h47877c9_openblas.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/liblzma-5.8.3-hb03c661_0.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/libnsl-2.0.1-hb9d3cd8_1.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/libopenblas-0.3.33-pthreads_h94d23a6_0.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/libpng-1.6.58-h421ea60_0.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/libraqm-0.10.5-h6406941_1.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/libsqlite-3.53.3-h0c1763c_0.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/libstdcxx-15.2.0-h934c35e_19.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/libstdcxx-ng-15.2.0-hdf11a46_19.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/libtiff-4.7.2-h9d88235_0.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/libuuid-2.42.2-h5347b49_0.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/libwebp-base-1.6.0-hd42ef1d_0.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/libxcb-1.17.0-h8a09558_0.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/libxcrypt-4.4.36-hd590300_1.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/libzlib-1.3.2-h25fd6f3_2.conda + - conda: https://conda.anaconda.org/conda-forge/noarch/markdown-it-py-4.2.0-pyhd8ed1ab_0.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/matplotlib-base-3.11.0-py312hc1765e9_1.conda + - conda: https://conda.anaconda.org/conda-forge/noarch/mdurl-0.1.2-pyhd8ed1ab_1.conda + - conda: https://conda.anaconda.org/conda-forge/noarch/munkres-1.1.4-pyhd8ed1ab_1.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/mypy-2.1.0-py312h574c966_0.conda + - conda: https://conda.anaconda.org/conda-forge/noarch/mypy_extensions-1.1.0-pyha770c72_0.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/ncurses-6.6-hdb14827_0.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/numpy-2.5.1-py312h33ff503_0.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/openjpeg-2.5.4-h55fea9a_0.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/openssl-3.6.3-h35e630c_0.conda + - conda: https://conda.anaconda.org/conda-forge/noarch/packaging-26.2-pyhc364b38_0.conda + - conda: https://conda.anaconda.org/conda-forge/noarch/pathspec-1.1.1-pyhd8ed1ab_0.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/pcre2-10.47-haa7fec5_0.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/pillow-12.3.0-py312h50c33e8_0.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/pixman-0.46.4-h54a6638_1.conda + - conda: https://conda.anaconda.org/conda-forge/noarch/pluggy-1.6.0-pyhf9edf01_1.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/psutil-7.2.2-py312h5253ce2_0.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/pthread-stubs-0.4-hb9d3cd8_1002.conda + - conda: https://conda.anaconda.org/conda-forge/noarch/pydantic-2.13.4-pyhcf101f3_0.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/pydantic-core-2.46.4-py312h868fb18_0.conda + - conda: https://conda.anaconda.org/conda-forge/noarch/pygments-2.20.0-pyhd8ed1ab_0.conda + - conda: https://conda.anaconda.org/conda-forge/noarch/pyparsing-3.3.2-pyhcf101f3_0.conda + - conda: https://conda.anaconda.org/conda-forge/noarch/pytest-9.1.1-pyhc364b38_2.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/python-3.12.13-hd63d673_0_cpython.conda + - conda: https://conda.anaconda.org/conda-forge/noarch/python-dateutil-2.9.0.post0-pyhe01879c_2.conda + - conda: https://conda.anaconda.org/conda-forge/noarch/python-gil-3.12.13-hd8ed1ab_0.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/python-librt-0.12.0-py312h5253ce2_0.conda + - conda: https://conda.anaconda.org/conda-forge/noarch/python_abi-3.12-8_cp312.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/qhull-2020.2-h434a139_5.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/readline-8.3-h853b02a_0.conda + - conda: https://conda.anaconda.org/conda-forge/noarch/rich-15.0.0-pyhcf101f3_0.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/ruff-0.15.20-h6a952e8_0.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/scipy-1.18.0-py312h54fa4ab_0.conda + - conda: https://conda.anaconda.org/conda-forge/noarch/shellingham-1.5.4-pyhd8ed1ab_2.conda + - conda: https://conda.anaconda.org/conda-forge/noarch/six-1.17.0-pyhe01879c_1.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/tk-8.6.13-noxft_h366c992_103.conda + - conda: https://conda.anaconda.org/conda-forge/noarch/tomli-2.4.1-pyhcf101f3_0.conda + - conda: https://conda.anaconda.org/conda-forge/noarch/tomlkit-0.15.0-pyha770c72_0.conda + - conda: https://conda.anaconda.org/conda-forge/noarch/typer-0.26.8-pyhcf101f3_0.conda + - conda: https://conda.anaconda.org/conda-forge/noarch/typing-extensions-4.16.0-h69aa097_0.conda + - conda: https://conda.anaconda.org/conda-forge/noarch/typing-inspection-0.4.2-pyhcf101f3_2.conda + - conda: https://conda.anaconda.org/conda-forge/noarch/typing_extensions-4.16.0-pyhcf101f3_0.conda + - conda: https://conda.anaconda.org/conda-forge/noarch/tzdata-2025c-hc9c84f9_1.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/unicodedata2-17.0.1-py312h4c3975b_0.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/xorg-libice-1.1.2-hb9d3cd8_0.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/xorg-libsm-1.2.6-he73a12e_0.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/xorg-libx11-1.8.13-he1eb515_0.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/xorg-libxau-1.0.12-hb03c661_1.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/xorg-libxdmcp-1.1.5-hb03c661_1.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/xorg-libxext-1.3.7-hb03c661_0.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/xorg-libxrender-0.9.12-hb9d3cd8_0.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/zlib-ng-2.3.3-hceb46e0_1.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/zstd-1.5.7-hb78ec9c_6.conda + - pypi: https://files.pythonhosted.org/packages/b0/7b/90df4a0a816d98d6ea26f559d87836d494a2cf1fcf063be67df50a7bcc30/anyio-4.14.1-py3-none-any.whl + - pypi: https://files.pythonhosted.org/packages/64/b4/17d4b0b2a2dc85a6df63d1157e028ed19f90d4cd97c36717afef2bc2f395/attrs-26.1.0-py3-none-any.whl + - pypi: https://files.pythonhosted.org/packages/ef/2f/c5464532e965badff2f4c4c1a3a83f5697f0d7c407ed0cda44aaa99bb451/certifi-2026.6.17-py3-none-any.whl + - pypi: https://files.pythonhosted.org/packages/62/f2/c9522a81c32132799a1972c39f5c5f8b4c8b9f00488a23feaa6c06f07741/cffi-2.1.0-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.whl + - pypi: https://files.pythonhosted.org/packages/fb/e2/79c688af8b210d232694e31e59da9f6ec747bae31c3f5946e4e9b98860d5/click-8.4.2-py3-none-any.whl + - pypi: https://files.pythonhosted.org/packages/20/2c/0622f20ff02b2ef32558733443805dc82fd4c275be01b2d19d14676f3a1b/cryptography-49.0.0-cp311-abi3-manylinux_2_28_x86_64.whl + - pypi: https://files.pythonhosted.org/packages/9e/7c/8e3c6ad324ea5cb36604fc3f968554887891c316d9dfde57761611d907ad/fastapi-0.139.0-py3-none-any.whl + - pypi: https://files.pythonhosted.org/packages/04/4b/29cac41a4d98d144bf5f6d33995617b185d14b22401f75ca86f384e87ff1/h11-0.16.0-py3-none-any.whl + - pypi: https://files.pythonhosted.org/packages/7e/f5/f66802a942d491edb555dd61e3a9961140fd64c90bce1eafd741609d334d/httpcore-1.0.9-py3-none-any.whl + - pypi: https://files.pythonhosted.org/packages/2a/39/e50c7c3a983047577ee07d2a9e53faf5a69493943ec3f6a384bdc792deb2/httpx-0.28.1-py3-none-any.whl + - pypi: https://files.pythonhosted.org/packages/d2/fd/6668e5aec43ab844de6fc74927e155a3b37bf40d7c3790e49fc0406b6578/httpx_sse-0.4.3-py3-none-any.whl + - pypi: https://files.pythonhosted.org/packages/1e/5e/d4e9f1a599fb8e573b7b87160658329fbf28d19eac2718f51fc3def3aa5a/idna-3.18-py3-none-any.whl + - pypi: https://files.pythonhosted.org/packages/69/90/f63fb5873511e014207a475e2bb4e8b2e570d655b00ac19a9a0ca0a385ee/jsonschema-4.26.0-py3-none-any.whl + - pypi: https://files.pythonhosted.org/packages/41/45/1a4ed80516f02155c51f51e8cedb3c1902296743db0bbc66608a0db2814f/jsonschema_specifications-2025.9.1-py3-none-any.whl + - pypi: https://files.pythonhosted.org/packages/e2/5e/d118fce19f87a2e7d8101c35c8ae0ec289098a4df0ff244cec23e415aca0/mcp-1.28.1-py3-none-any.whl + - pypi: https://files.pythonhosted.org/packages/0c/c3/44f3fbbfa403ea2a7c779186dc20772604442dde72947e7d01069cbe98e3/pycparser-3.0-py3-none-any.whl + - pypi: https://files.pythonhosted.org/packages/77/c1/6e422f34e569cf8e18df68d1939c81c099d2b61e4f7d9621c8a77560799c/pydantic_settings-2.14.2-py3-none-any.whl + - pypi: https://files.pythonhosted.org/packages/a3/5e/ecf12fdb62546d64385c158514e9b2b671f7832108ef2ecd2020ce0af2d1/pyjwt-2.13.0-py3-none-any.whl + - pypi: https://files.pythonhosted.org/packages/0b/d7/1959b9648791274998a9c3526f6d0ec8fd2233e4d4acce81bbae76b44b2a/python_dotenv-1.2.2-py3-none-any.whl + - pypi: https://files.pythonhosted.org/packages/e1/04/e8135ebd1ad02c56ec633277529b2602ff99ff634be76cdba5744cf554fd/python_multipart-0.0.32-py3-none-any.whl + - pypi: https://files.pythonhosted.org/packages/2c/58/ca301544e1fa93ed4f80d724bf5b194f6e4b945841c5bfd555878eea9fcb/referencing-0.37.0-py3-none-any.whl + - pypi: https://files.pythonhosted.org/packages/04/8f/d2f3f532616be4d06c316ef119683e832bd3d41e112bf3a88f4151c95b17/rpds_py-2026.6.3-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl + - pypi: https://files.pythonhosted.org/packages/78/75/c88d3f5dafd59c791da1ce27650d30bf5b70cbf1cbf01cd00e5f9e360915/sse_starlette-3.4.5-py3-none-any.whl + - pypi: https://files.pythonhosted.org/packages/ec/bb/2799cc2ede3ed41131f8975621e7213dfc7ef4acbbaadfa440f32500c370/starlette-1.3.1-py3-none-any.whl + - pypi: https://files.pythonhosted.org/packages/aa/f0/7c228ee10c7ab8fd3a21d06579a6f7c6075c6ce72594a20fb5d2f206ff24/uvicorn-0.50.2-py3-none-any.whl + - pypi: ./ packages: - conda: https://conda.anaconda.org/conda-forge/linux-64/_openmp_mutex-4.5-20_gnu.conda build_number: 20 @@ -696,6 +851,17 @@ packages: purls: [] size: 28948 timestamp: 1770939786096 +- conda: https://conda.anaconda.org/conda-forge/noarch/_python_abi3_support-1.0-hd8ed1ab_2.conda + sha256: a3967b937b9abf0f2a99f3173fa4630293979bd1644709d89580e7c62a544661 + md5: aaa2a381ccc56eac91d63b6c1240312f + depends: + - cpython + - python-gil + license: MIT + license_family: MIT + purls: [] + size: 8191 + timestamp: 1744137672556 - conda: https://conda.anaconda.org/conda-forge/noarch/annotated-doc-0.0.4-pyhcf101f3_0.conda sha256: cc9fbc50d4ee7ee04e49ee119243e6f1765750f0fd0b4d270d5ef35461b643b1 md5: 52be5139047efadaeeb19c6a5103f92a @@ -720,6 +886,16 @@ packages: - pkg:pypi/annotated-types?source=hash-mapping size: 18074 timestamp: 1733247158254 +- pypi: https://files.pythonhosted.org/packages/b0/7b/90df4a0a816d98d6ea26f559d87836d494a2cf1fcf063be67df50a7bcc30/anyio-4.14.1-py3-none-any.whl + name: anyio + version: 4.14.1 + sha256: 4e5533c5b8ff0a24f5d7a176cbe6877129cd183893f66b537f8f227d10527d72 + requires_dist: + - exceptiongroup>=1.0.2 ; python_full_version < '3.11' + - idna>=2.8 + - typing-extensions>=4.5 ; python_full_version < '3.13' + - trio>=0.32.0 ; extra == 'trio' + requires_python: '>=3.10' - conda: https://conda.anaconda.org/conda-forge/noarch/ase-3.28.0-pyhd8ed1ab_1.conda sha256: e8dfb53868c22aa3d1beb0d93c868acb9f0bfe403fea4278a21f528b003b4761 md5: 87e6b0b9a7d54dc0c593e394ed8e10ef @@ -733,6 +909,43 @@ packages: - pkg:pypi/ase?source=hash-mapping size: 1911913 timestamp: 1774510723416 +- conda: https://conda.anaconda.org/conda-forge/noarch/ase-3.29.0-pyhd8ed1ab_1.conda + sha256: 287dbf2b1b20a5caaa0021887aeba5c7fde20c89879338a4ab84115d972ee76b + md5: aa59c152ba5bcaf269e6782dc1cbd5a7 + depends: + - matplotlib-base + - numpy + - python >=3.10 + - scipy + - typing_extensions + license: LGPL-2.1-or-later + purls: + - pkg:pypi/ase?source=hash-mapping + size: 1967089 + timestamp: 1782119236327 +- conda: https://conda.anaconda.org/conda-forge/linux-64/ast-serialize-0.6.0-py310hd8a072f_0.conda + noarch: python + sha256: 98eef90c96e2185254d12e667337077b989e9892167ff2c969e19b9296f42743 + md5: 530aaeffb462b062bf8e3abb66879cf0 + depends: + - python >=3.10 + - __glibc >=2.17,<3.0.a0 + - libgcc >=14 + - _python_abi3_support 1.* + - cpython >=3.10 + constrains: + - __glibc >=2.17 + license: MIT + license_family: MIT + purls: + - pkg:pypi/ast-serialize?source=hash-mapping + size: 1120486 + timestamp: 1782863830347 +- pypi: https://files.pythonhosted.org/packages/64/b4/17d4b0b2a2dc85a6df63d1157e028ed19f90d4cd97c36717afef2bc2f395/attrs-26.1.0-py3-none-any.whl + name: attrs + version: 26.1.0 + sha256: c647aa4a12dfbad9333ca4e71fe62ddc36f4e63b2d260a37a8b83d2f043ac309 + requires_python: '>=3.9' - pypi: https://files.pythonhosted.org/packages/77/f5/21d2de20e8b8b0408f0681956ca2c69f1320a3848ac50e6e7f39c6159675/babel-2.18.0-py3-none-any.whl name: babel version: 2.18.0 @@ -844,6 +1057,15 @@ packages: purls: [] size: 129868 timestamp: 1779289852439 +- conda: https://conda.anaconda.org/conda-forge/noarch/ca-certificates-2026.6.17-hbd8a1cb_0.conda + sha256: f8e3c730fa14ee3f170493779f06522c4acf89169f43db4f039727709b6419cf + md5: a9965dd99f683c5f444428f896635716 + depends: + - __unix + license: ISC + purls: [] + size: 128866 + timestamp: 1781708962055 - conda: https://conda.anaconda.org/conda-forge/linux-64/cairo-1.18.4-he90730b_1.conda sha256: 06525fa0c4e4f56e771a3b986d0fdf0f0fc5a3270830ee47e127a5105bde1b9a md5: bb6c4808bfa69d6f7f6b07e5846ced37 @@ -876,6 +1098,11 @@ packages: version: 2026.5.20 sha256: 3c52e209ba0a4ad7aebe60436a4ab349c39e1e602e8c134221e546902ad25897 requires_python: '>=3.7' +- pypi: https://files.pythonhosted.org/packages/ef/2f/c5464532e965badff2f4c4c1a3a83f5697f0d7c407ed0cda44aaa99bb451/certifi-2026.6.17-py3-none-any.whl + name: certifi + version: 2026.6.17 + sha256: 2227dcbaafe0d2f59279d1762ddddc37783ed4354594f194ffc31d20f41fc3db + requires_python: '>=3.7' - conda: https://conda.anaconda.org/conda-forge/noarch/certifi-2026.5.20-pyhd8ed1ab_0.conda sha256: 645655a3510e38e625da136595f3f16f2130c3263630cc3bc8f60f619ddbe490 md5: 9fefff2f745ea1cc2ef15211a20c054a @@ -886,6 +1113,13 @@ packages: - pkg:pypi/certifi?source=compressed-mapping size: 134201 timestamp: 1779285131141 +- pypi: https://files.pythonhosted.org/packages/62/f2/c9522a81c32132799a1972c39f5c5f8b4c8b9f00488a23feaa6c06f07741/cffi-2.1.0-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.whl + name: cffi + version: 2.1.0 + sha256: 1e9f50d192a3e525b15a75ab5114e442d83d657b7ec29182a991bc9a88fd3a66 + requires_dist: + - pycparser ; implementation_name != 'PyPy' + requires_python: '>=3.10' - conda: https://conda.anaconda.org/conda-forge/linux-64/cffi-2.0.0-py312h460c074_1.conda sha256: 7dafe8173d5f94e46cf9cd597cc8ff476a8357fbbd4433a8b5697b2864845d9c md5: 648ee28dcd4e07a1940a17da62eccd40 @@ -925,6 +1159,13 @@ packages: requires_dist: - colorama ; sys_platform == 'win32' requires_python: '>=3.10' +- pypi: https://files.pythonhosted.org/packages/fb/e2/79c688af8b210d232694e31e59da9f6ec747bae31c3f5946e4e9b98860d5/click-8.4.2-py3-none-any.whl + name: click + version: 8.4.2 + sha256: e6f9f66136c816745b9d65817da91d61d957fb16e02e4dcd0552553c5a197b76 + requires_dist: + - colorama ; sys_platform == 'win32' + requires_python: '>=3.10' - conda: https://conda.anaconda.org/conda-forge/noarch/colorama-0.4.6-pyhd8ed1ab_1.conda sha256: ab29d57dc70786c1269633ba3dff20288b81664d3ff8d21af995742e2bb03287 md5: 962b9857ee8e7018c22f2776ffa0b2d7 @@ -977,6 +1218,15 @@ packages: purls: [] size: 46463 timestamp: 1772728929620 +- pypi: https://files.pythonhosted.org/packages/20/2c/0622f20ff02b2ef32558733443805dc82fd4c275be01b2d19d14676f3a1b/cryptography-49.0.0-cp311-abi3-manylinux_2_28_x86_64.whl + name: cryptography + version: 49.0.0 + sha256: 2afe9051da7ae7bd5905da5a949280c7d2bb75682e188f650a9d0f2756b834c6 + requires_dist: + - cffi>=2.0.0 ; platform_python_implementation != 'PyPy' + - typing-extensions>=4.13.2 ; python_full_version < '3.11' + - bcrypt>=3.1.5 ; extra == 'ssh' + requires_python: '>=3.9,!=3.9.0,!=3.9.1' - pypi: https://files.pythonhosted.org/packages/04/40/a2ea4d8f032bfd6c220d50b6f92cd61f33d48f31959da39ed1b178cfee54/cuda_bindings-13.3.0-cp312-cp312-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl name: cuda-bindings version: 13.3.0 @@ -1147,6 +1397,44 @@ packages: - pkg:pypi/exceptiongroup?source=hash-mapping size: 21333 timestamp: 1763918099466 +- pypi: https://files.pythonhosted.org/packages/9e/7c/8e3c6ad324ea5cb36604fc3f968554887891c316d9dfde57761611d907ad/fastapi-0.139.0-py3-none-any.whl + name: fastapi + version: 0.139.0 + sha256: cf15e1e9e667ddb0ad63811e60bd11390d1aac838ca4a7a23f421807b2308189 + requires_dist: + - starlette>=0.46.0 + - pydantic>=2.9.0 + - typing-extensions>=4.8.0 + - typing-inspection>=0.4.2 + - annotated-doc>=0.0.2 + - fastapi-cli[standard]>=0.0.8 ; extra == 'standard' + - fastar>=0.9.0 ; extra == 'standard' + - httpx>=0.23.0,<1.0.0 ; extra == 'standard' + - jinja2>=3.1.5 ; extra == 'standard' + - python-multipart>=0.0.18 ; extra == 'standard' + - email-validator>=2.0.0 ; extra == 'standard' + - uvicorn[standard]>=0.12.0 ; extra == 'standard' + - pydantic-settings>=2.0.0 ; extra == 'standard' + - pydantic-extra-types>=2.0.0 ; extra == 'standard' + - fastapi-cli[standard-no-fastapi-cloud-cli]>=0.0.8 ; extra == 'standard-no-fastapi-cloud-cli' + - httpx>=0.23.0,<1.0.0 ; extra == 'standard-no-fastapi-cloud-cli' + - jinja2>=3.1.5 ; extra == 'standard-no-fastapi-cloud-cli' + - python-multipart>=0.0.18 ; extra == 'standard-no-fastapi-cloud-cli' + - email-validator>=2.0.0 ; extra == 'standard-no-fastapi-cloud-cli' + - uvicorn[standard]>=0.12.0 ; extra == 'standard-no-fastapi-cloud-cli' + - pydantic-settings>=2.0.0 ; extra == 'standard-no-fastapi-cloud-cli' + - pydantic-extra-types>=2.0.0 ; extra == 'standard-no-fastapi-cloud-cli' + - fastapi-cli[standard]>=0.0.8 ; extra == 'all' + - httpx>=0.23.0,<1.0.0 ; extra == 'all' + - jinja2>=3.1.5 ; extra == 'all' + - python-multipart>=0.0.18 ; extra == 'all' + - itsdangerous>=1.1.0 ; extra == 'all' + - pyyaml>=5.3.1 ; extra == 'all' + - email-validator>=2.0.0 ; extra == 'all' + - uvicorn[standard]>=0.12.0 ; extra == 'all' + - pydantic-settings>=2.0.0 ; extra == 'all' + - pydantic-extra-types>=2.0.0 ; extra == 'all' + requires_python: '>=3.10' - pypi: https://files.pythonhosted.org/packages/81/47/dd9a212ef6e343a6857485ffe25bba537304f1913bdbed446a23f7f592e1/filelock-3.29.0-py3-none-any.whl name: filelock version: 3.29.0 @@ -1200,6 +1488,22 @@ packages: purls: [] size: 280882 timestamp: 1779421631622 +- conda: https://conda.anaconda.org/conda-forge/linux-64/fontconfig-2.18.1-h27c8c51_0.conda + sha256: 2e50bdcebdf70a865b81f2456bbc586386451ec601c60f2b6cd22b8c40a2d384 + md5: e0e050cfa9fa85fe39632ab11cb7f3e0 + depends: + - __glibc >=2.17,<3.0.a0 + - libexpat >=2.8.1,<3.0a0 + - libfreetype >=2.14.3 + - libfreetype6 >=2.14.3 + - libgcc >=14 + - libuuid >=2.42.1,<3.0a0 + - libzlib >=1.3.2,<2.0a0 + license: MIT + license_family: MIT + purls: [] + size: 281880 + timestamp: 1780450077431 - conda: https://conda.anaconda.org/conda-forge/noarch/fonts-conda-ecosystem-1-0.tar.bz2 sha256: a997f2f1921bb9c9d76e6fa2f6b408b7fa549edd349a77639c9fe7a23ea93e61 md5: fee5683a3f04bd15cbd8318b096a27ab @@ -1262,6 +1566,16 @@ packages: - pkg:pypi/freetype-py?source=hash-mapping size: 58932 timestamp: 1650983451848 +- conda: https://conda.anaconda.org/conda-forge/linux-64/fribidi-1.0.16-hb03c661_0.conda + sha256: 858283ff33d4c033f4971bf440cebff217d5552a5222ba994c49be990dacd40d + md5: f9f81ea472684d75b9dd8d0b328cf655 + depends: + - __glibc >=2.17,<3.0.a0 + - libgcc >=14 + license: LGPL-2.1-or-later + purls: [] + size: 61244 + timestamp: 1757438574066 - pypi: https://files.pythonhosted.org/packages/d5/0c/043d5e551459da400957a1395e0febbf771446ff34291afcbe3d8be2a279/fsspec-2026.4.0-py3-none-any.whl name: fsspec version: 2026.4.0 @@ -1447,6 +1761,18 @@ packages: - pkg:pypi/gmpy2?source=hash-mapping size: 253171 timestamp: 1773245116314 +- conda: https://conda.anaconda.org/conda-forge/linux-64/graphite2-1.3.15-hecca717_0.conda + sha256: 885fa7d1d7e2ad9ed0a700ee0d81ceb49de278253082d517959b22d6336eecce + md5: cf09e9fc938518e91d0706572cadf17a + depends: + - __glibc >=2.17,<3.0.a0 + - libgcc >=14 + - libstdcxx >=14 + license: LGPL-2.0-or-later + license_family: LGPL + purls: [] + size: 100054 + timestamp: 1780454302233 - conda: https://conda.anaconda.org/conda-forge/linux-64/greenlet-3.5.1-py312h8285ef7_0.conda sha256: 9f071d4d4efb41b54c671539fd9f9c29589f96f0d4fb457545a4b144e2545644 md5: 3a704672326e552b019390d832a4b095 @@ -1471,6 +1797,11 @@ packages: - platformdirs>=4.2 ; extra == 'pypi' - wheel>=0.42 ; extra == 'pypi' requires_python: '>=3.10' +- pypi: https://files.pythonhosted.org/packages/04/4b/29cac41a4d98d144bf5f6d33995617b185d14b22401f75ca86f384e87ff1/h11-0.16.0-py3-none-any.whl + name: h11 + version: 0.16.0 + sha256: 63cf8bbe7522de3bf65932fda1d9c2772064ffb3dae62d55932da54b31cb6c86 + requires_python: '>=3.8' - conda: https://conda.anaconda.org/conda-forge/noarch/h2-4.3.0-pyhcf101f3_0.conda sha256: 84c64443368f84b600bfecc529a1194a3b14c3656ee2e832d15a20e0329b6da3 md5: 164fc43f0b53b6e3a7bc7dce5e4f1dc9 @@ -1518,6 +1849,41 @@ packages: - pkg:pypi/hpack?source=hash-mapping size: 30731 timestamp: 1737618390337 +- pypi: https://files.pythonhosted.org/packages/7e/f5/f66802a942d491edb555dd61e3a9961140fd64c90bce1eafd741609d334d/httpcore-1.0.9-py3-none-any.whl + name: httpcore + version: 1.0.9 + sha256: 2d400746a40668fc9dec9810239072b40b4484b640a8c38fd654a024c7a1bf55 + requires_dist: + - certifi + - h11>=0.16 + - anyio>=4.0,<5.0 ; extra == 'asyncio' + - h2>=3,<5 ; extra == 'http2' + - socksio==1.* ; extra == 'socks' + - trio>=0.22.0,<1.0 ; extra == 'trio' + requires_python: '>=3.8' +- pypi: https://files.pythonhosted.org/packages/2a/39/e50c7c3a983047577ee07d2a9e53faf5a69493943ec3f6a384bdc792deb2/httpx-0.28.1-py3-none-any.whl + name: httpx + version: 0.28.1 + sha256: d909fcccc110f8c7faf814ca82a9a4d816bc5a6dbfea25d6591d6985b8ba59ad + requires_dist: + - anyio + - certifi + - httpcore==1.* + - idna + - brotli ; platform_python_implementation == 'CPython' and extra == 'brotli' + - brotlicffi ; platform_python_implementation != 'CPython' and extra == 'brotli' + - click==8.* ; extra == 'cli' + - pygments==2.* ; extra == 'cli' + - rich>=10,<14 ; extra == 'cli' + - h2>=3,<5 ; extra == 'http2' + - socksio==1.* ; extra == 'socks' + - zstandard>=0.18.0 ; extra == 'zstd' + requires_python: '>=3.8' +- pypi: https://files.pythonhosted.org/packages/d2/fd/6668e5aec43ab844de6fc74927e155a3b37bf40d7c3790e49fc0406b6578/httpx_sse-0.4.3-py3-none-any.whl + name: httpx-sse + version: 0.4.3 + sha256: 0ac1c9fe3c0afad2e0ebb25a934a59f4c7823b60792691f779fad2c5568830fc + requires_python: '>=3.9' - conda: https://conda.anaconda.org/conda-forge/noarch/hyperframe-6.1.0-pyhd8ed1ab_0.conda sha256: 77af6f5fe8b62ca07d09ac60127a30d9069fdc3c68d6b256754d0ffb1f7779f8 md5: 8e6923fc12f1fe8f8c4e5c9f343256ac @@ -1550,6 +1916,15 @@ packages: - mypy>=1.11.2 ; extra == 'all' - pytest>=8.3.2 ; extra == 'all' requires_python: '>=3.9' +- pypi: https://files.pythonhosted.org/packages/1e/5e/d4e9f1a599fb8e573b7b87160658329fbf28d19eac2718f51fc3def3aa5a/idna-3.18-py3-none-any.whl + name: idna + version: '3.18' + sha256: 7f952cbe720b688055e3f87de14f5c3e5fdaa8bc3928985c4077ca689de849a2 + requires_dist: + - ruff>=0.6.2 ; extra == 'all' + - mypy>=1.11.2 ; extra == 'all' + - pytest>=8.3.2 ; extra == 'all' + requires_python: '>=3.9' - conda: https://conda.anaconda.org/conda-forge/noarch/idna-3.17-pyhcf101f3_0.conda sha256: f9fe1f9e539c544405ccb7ba632d4ba79edf243c05554d76ace073158a80b691 md5: c75e517ebd7a5c5272fe111e8b162228 @@ -1643,6 +2018,40 @@ packages: purls: [] size: 109177 timestamp: 1774958820636 +- pypi: https://files.pythonhosted.org/packages/69/90/f63fb5873511e014207a475e2bb4e8b2e570d655b00ac19a9a0ca0a385ee/jsonschema-4.26.0-py3-none-any.whl + name: jsonschema + version: 4.26.0 + sha256: d489f15263b8d200f8387e64b4c3a75f06629559fb73deb8fdfb525f2dab50ce + requires_dist: + - attrs>=22.2.0 + - jsonschema-specifications>=2023.3.6 + - referencing>=0.28.4 + - rpds-py>=0.25.0 + - fqdn ; extra == 'format' + - idna ; extra == 'format' + - isoduration ; extra == 'format' + - jsonpointer>1.13 ; extra == 'format' + - rfc3339-validator ; extra == 'format' + - rfc3987 ; extra == 'format' + - uri-template ; extra == 'format' + - webcolors>=1.11 ; extra == 'format' + - fqdn ; extra == 'format-nongpl' + - idna ; extra == 'format-nongpl' + - isoduration ; extra == 'format-nongpl' + - jsonpointer>1.13 ; extra == 'format-nongpl' + - rfc3339-validator ; extra == 'format-nongpl' + - rfc3986-validator>0.1.0 ; extra == 'format-nongpl' + - rfc3987-syntax>=1.1.0 ; extra == 'format-nongpl' + - uri-template ; extra == 'format-nongpl' + - webcolors>=24.6.0 ; extra == 'format-nongpl' + requires_python: '>=3.10' +- pypi: https://files.pythonhosted.org/packages/41/45/1a4ed80516f02155c51f51e8cedb3c1902296743db0bbc66608a0db2814f/jsonschema_specifications-2025.9.1-py3-none-any.whl + name: jsonschema-specifications + version: 2025.9.1 + sha256: 98802fee3a11ee76ecaca44429fda8a41bff98b00a0f2838151b113f210cc6fe + requires_dist: + - referencing>=0.31.0 + requires_python: '>=3.9' - conda: https://conda.anaconda.org/conda-forge/linux-64/keyutils-1.6.3-hb9d3cd8_0.conda sha256: 0960d06048a7185d3542d850986d807c6e37ca2e644342dd0c72feefcf26c2a4 md5: b38117a3c920364aff79f870c984b4a3 @@ -1709,6 +2118,19 @@ packages: purls: [] size: 251086 timestamp: 1778079286384 +- conda: https://conda.anaconda.org/conda-forge/linux-64/lcms2-2.19.1-h0c24ade_1.conda + sha256: 112b5b9462572d970f4abd2912f76a25ee7db158b1e7260163d91dd8a630db84 + md5: 8b3ce45e929cd8e8e5f4d18586b56d8b + depends: + - __glibc >=2.17,<3.0.a0 + - libgcc >=14 + - libjpeg-turbo >=3.1.4.1,<4.0a0 + - libtiff >=4.7.1,<4.8.0a0 + license: MIT + license_family: MIT + purls: [] + size: 251971 + timestamp: 1780211695895 - conda: https://conda.anaconda.org/conda-forge/linux-64/ld_impl_linux-64-2.45.1-default_hbd61a6d_102.conda sha256: 3d584956604909ff5df353767f3a2a2f60e07d070b328d109f30ac40cd62df6c md5: 18335a698559cdbcd86150a48bf54ba6 @@ -1875,6 +2297,19 @@ packages: purls: [] size: 77294 timestamp: 1779278686680 +- conda: https://conda.anaconda.org/conda-forge/linux-64/libexpat-2.8.1-hecca717_1.conda + sha256: 16feffd9ddbbe5b718515d38ee376c685ba95491cd901244e24671d20b952a77 + md5: b24d3c612f71e7aa74158d92106318b2 + depends: + - __glibc >=2.17,<3.0.a0 + - libgcc >=14 + constrains: + - expat 2.8.1.* + license: MIT + license_family: MIT + purls: [] + size: 77856 + timestamp: 1781203599810 - conda: https://conda.anaconda.org/conda-forge/linux-64/libffi-3.5.2-h3435931_0.conda sha256: 31f19b6a88ce40ebc0d5a992c131f57d919f73c0b92cd1617a5bec83f6e961e6 md5: a360c33a5abe61c07959e449fa1453eb @@ -1974,6 +2409,22 @@ packages: purls: [] size: 4754097 timestamp: 1778508800134 +- conda: https://conda.anaconda.org/conda-forge/linux-64/libglib-2.88.2-h0d30a3d_0.conda + sha256: 4bee10e62796f01e4fa2b5849135b1cc061337fe9cf5eb9bd79e9664922ae0e4 + md5: 889febc66cd9e4190f80ef9718fa239b + depends: + - libgcc >=14 + - __glibc >=2.17,<3.0.a0 + - libiconv >=1.18,<2.0a0 + - libzlib >=1.3.2,<2.0a0 + - libffi >=3.5.2,<3.6.0a0 + - pcre2 >=10.47,<10.48.0a0 + constrains: + - glib >2.66 + license: LGPL-2.1-or-later + purls: [] + size: 4754220 + timestamp: 1782463895250 - conda: https://conda.anaconda.org/conda-forge/linux-64/libgomp-15.2.0-he0feb66_19.conda sha256: 5abe4ab9d93f6c9757d654f1969ae2267d4505315c1f2f8fe705fd60af084f1b md5: faac990cb7aedc7f3a2224f2c9b0c26c @@ -1984,6 +2435,26 @@ packages: purls: [] size: 603817 timestamp: 1778268942614 +- conda: https://conda.anaconda.org/conda-forge/linux-64/libharfbuzz-14.2.1-h17a8019_1.conda + sha256: 821c315f6b5171aa89e735be2ad84e74eb3f898fc7610ee36cfecd95dfa789e8 + md5: fb4669c3990b94ea32fbb81f433e9aa6 + depends: + - __glibc >=2.17,<3.0.a0 + - cairo >=1.18.4,<2.0a0 + - graphite2 >=1.3.15,<2.0a0 + - icu >=78.3,<79.0a0 + - libfreetype >=2.14.3 + - libfreetype6 >=2.14.3 + - libgcc >=14 + - libglib >=2.88.2,<3.0a0 + - libpng >=1.6.58,<1.7.0a0 + - libstdcxx >=14 + - libzlib >=1.3.2,<2.0a0 + license: MIT + license_family: MIT + purls: [] + size: 1297668 + timestamp: 1782800580119 - conda: https://conda.anaconda.org/conda-forge/linux-64/libiconv-1.18-h3b78370_2.conda sha256: c467851a7312765447155e071752d7bf9bf44d610a5687e32706f480aad2833f md5: 915f5995e94f60e9a4826e0b0920ee88 @@ -2094,6 +2565,21 @@ packages: purls: [] size: 2754709 timestamp: 1778786234149 +- conda: https://conda.anaconda.org/conda-forge/linux-64/libraqm-0.10.5-h6406941_1.conda + sha256: 7c9e562842f193f772ef0ba681f238a2d9e5ef637588b6e46eb30cc6aa1940c8 + md5: fa63517815747363c41b439ff9301db1 + depends: + - __glibc >=2.28,<3.0.a0 + - libgcc >=14 + - libharfbuzz >=14.2.1 + - libfreetype >=2.14.3 + - libfreetype6 >=2.14.3 + - fribidi >=1.0.16,<2.0a0 + license: MIT + license_family: MIT + purls: [] + size: 29441 + timestamp: 1782807076031 - conda: https://conda.anaconda.org/conda-forge/linux-64/librdkit-2026.03.2-h7442aff_5.conda sha256: 202eb9c7301d75755b2a322953d9e594498d5483a204144cb9c0c586e5aed8c2 md5: f472f725063b27207c0bf072388256c5 @@ -2122,6 +2608,17 @@ packages: purls: [] size: 954962 timestamp: 1777986471789 +- conda: https://conda.anaconda.org/conda-forge/linux-64/libsqlite-3.53.3-h0c1763c_0.conda + sha256: 365376f4815e5e80def2b3462a2419708b7c292da0da85278386c2618621fff4 + md5: 4aed8e657e9ff156bdbe849b4df44389 + depends: + - __glibc >=2.17,<3.0.a0 + - libgcc >=14 + - libzlib >=1.3.2,<2.0a0 + license: blessing + purls: [] + size: 962119 + timestamp: 1782519076616 - conda: https://conda.anaconda.org/conda-forge/linux-64/libstdcxx-15.2.0-h934c35e_19.conda sha256: dff1058c76ec6b8759e41cefa2508162d00e4a5e6721aa68ec3fd10094e702dc md5: 5794b3bdc38177caf969dabd3af08549 @@ -2163,6 +2660,24 @@ packages: purls: [] size: 435273 timestamp: 1762022005702 +- conda: https://conda.anaconda.org/conda-forge/linux-64/libtiff-4.7.2-h9d88235_0.conda + sha256: b31346e1c01ab40a170e91147092ee8fd92b1dee3c66ee47ef025571c879b159 + md5: c1fcb4a88bc15a9f77ad8d27d7af1df9 + depends: + - __glibc >=2.17,<3.0.a0 + - lerc >=4.1.0,<5.0a0 + - libdeflate >=1.25,<1.26.0a0 + - libgcc >=14 + - libjpeg-turbo >=3.1.4.1,<4.0a0 + - liblzma >=5.8.3,<6.0a0 + - libstdcxx >=14 + - libwebp-base >=1.6.0,<2.0a0 + - libzlib >=1.3.2,<2.0a0 + - zstd >=1.5.7,<1.6.0a0 + license: HPND + purls: [] + size: 452337 + timestamp: 1783084902636 - conda: https://conda.anaconda.org/conda-forge/linux-64/libuuid-2.42.1-h5347b49_0.conda sha256: 3f0edf1280e2f6684a986f821eaa3e123d2694a00b31b96ca0d4a4c12c129231 md5: 7d0a66598195ef00b6efc55aefc7453b @@ -2174,6 +2689,17 @@ packages: purls: [] size: 40163 timestamp: 1779118517630 +- conda: https://conda.anaconda.org/conda-forge/linux-64/libuuid-2.42.2-h5347b49_0.conda + sha256: 9b1bdce27a7e31f7d241aeecff67a1f3101d52a2b1e33ccc2cdf2613072bf81f + md5: 01bb81d12c957de066ea7362007df642 + depends: + - libgcc >=14 + - __glibc >=2.17,<3.0.a0 + license: BSD-3-Clause + license_family: BSD + purls: [] + size: 40017 + timestamp: 1781625522462 - conda: https://conda.anaconda.org/conda-forge/linux-64/libwebp-base-1.6.0-hd42ef1d_0.conda sha256: 3aed21ab28eddffdaf7f804f49be7a7d701e8f0e46c856d801270b470820a37b md5: aea31d2e5b1091feca96fcfe945c3cf9 @@ -2409,6 +2935,37 @@ packages: - pkg:pypi/matplotlib?source=hash-mapping size: 8336056 timestamp: 1777000573501 +- conda: https://conda.anaconda.org/conda-forge/linux-64/matplotlib-base-3.11.0-py312hc1765e9_1.conda + sha256: d983b4ea15841f1fde4ccba4370485e89e696a447fcf5e90a1f75c8487699c68 + md5: 1d06d24525cf2e373310c1131acf12f8 + depends: + - __glibc >=2.17,<3.0.a0 + - contourpy >=1.0.1 + - cycler >=0.10 + - fonttools >=4.22.0 + - freetype + - kiwisolver >=1.3.1 + - libfreetype >=2.14.3 + - libfreetype6 >=2.14.3 + - libgcc >=14 + - libraqm >=0.10.5,<0.11.0a0 + - libstdcxx >=14 + - numpy >=1.23 + - numpy >=1.25,<3 + - packaging >=20.0 + - pillow >=8 + - pyparsing >=2.3.1 + - python >=3.12,<3.13.0a0 + - python-dateutil >=2.7 + - python_abi 3.12.* *_cp312 + - qhull >=2020.2,<2020.3.0a0 + - tk >=8.6.13,<8.7.0a0 + license: PSF-2.0 + license_family: PSF + purls: + - pkg:pypi/matplotlib?source=compressed-mapping + size: 8877024 + timestamp: 1782829532714 - pypi: https://files.pythonhosted.org/packages/3c/ba/79020348dbdaa6786ff2162e11bc56095e0b949e8bb9813dee12ccc1f567/matscipy-1.2.0-cp312-cp312-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl name: matscipy version: 1.2.0 @@ -2440,6 +2997,33 @@ packages: - argcomplete ; extra == 'cli' - matscipy[cli,docs,test] ; extra == 'all' requires_python: '>=3.9.0' +- pypi: https://files.pythonhosted.org/packages/e2/5e/d118fce19f87a2e7d8101c35c8ae0ec289098a4df0ff244cec23e415aca0/mcp-1.28.1-py3-none-any.whl + name: mcp + version: 1.28.1 + sha256: 2726bca5e7193f61c5dde8b12500a6de2d9acf6d1a1c0be9e8c2e706437991df + requires_dist: + - anyio>=4.5 + - httpx-sse>=0.4 + - httpx>=0.27.1,<1.0.0 + - jsonschema>=4.20.0 + - pydantic-settings>=2.5.2 + - pydantic>=2.11.0,<3.0.0 ; python_full_version < '3.14' + - pydantic>=2.12.0,<3.0.0 ; python_full_version >= '3.14' + - pyjwt[crypto]>=2.10.1 + - python-multipart>=0.0.9 + - pywin32>=310 ; python_full_version < '3.14' and sys_platform == 'win32' + - pywin32>=311 ; python_full_version >= '3.14' and sys_platform == 'win32' + - sse-starlette>=1.6.1 + - starlette>=0.27 ; python_full_version < '3.14' + - starlette>=0.48.0 ; python_full_version >= '3.14' + - typing-extensions>=4.9.0 + - typing-inspection>=0.4.1 + - uvicorn>=0.31.1 ; sys_platform != 'emscripten' + - python-dotenv>=1.0.0 ; extra == 'cli' + - typer>=0.16.0 ; extra == 'cli' + - rich>=13.9.4 ; extra == 'rich' + - websockets>=15.0.1 ; extra == 'ws' + requires_python: '>=3.10' - conda: https://conda.anaconda.org/conda-forge/linux-64/mctc-lib-0.5.1-gfortran_h956d735_1.conda sha256: ff57eaddc0814e4a0b7d7f74133722395afa6c2421932185dd4baa1fbd5c1d0f md5: dec5ed91c43152cf702512ce1f785135 @@ -2691,6 +3275,26 @@ packages: - pkg:pypi/mypy?source=hash-mapping size: 22035539 timestamp: 1776802000447 +- conda: https://conda.anaconda.org/conda-forge/linux-64/mypy-2.1.0-py312h574c966_0.conda + sha256: 9dd69cd6b09ff86ad66bfe39fa9c0c5aeec2e94e0205f3c604af5886381f0bf3 + md5: f13bcd6fb39235fa118b01e2b813a957 + depends: + - ast-serialize >=0.3.0,<1.0.0 + - mypy_extensions >=1.0.0 + - pathspec >=1.0.0 + - python + - python-librt >=0.11.0 + - typing_extensions >=4.6.0 + - psutil >=4.0 + - __glibc >=2.17,<3.0.a0 + - libgcc >=14 + - python_abi 3.12.* *_cp312 + license: MIT + license_family: MIT + purls: + - pkg:pypi/mypy?source=hash-mapping + size: 22482657 + timestamp: 1780315607048 - conda: https://conda.anaconda.org/conda-forge/noarch/mypy_extensions-1.1.0-pyha770c72_0.conda sha256: 6ed158e4e5dd8f6a10ad9e525631e35cee8557718f83de7a4e3966b1f772c4b1 md5: e9c622e0d00fa24a6292279af3ab6d06 @@ -2813,6 +3417,26 @@ packages: - pkg:pypi/numpy?source=compressed-mapping size: 8759520 timestamp: 1779169200325 +- conda: https://conda.anaconda.org/conda-forge/linux-64/numpy-2.5.1-py312h33ff503_0.conda + sha256: 2941c4a5fee88fe1c91c0d95b65e3a292d078f6655b53ff60f4813a44349c83e + md5: 3b7525d598ec0d0365ebd2378160a02f + depends: + - python + - libstdcxx >=14 + - libgcc >=14 + - __glibc >=2.17,<3.0.a0 + - libcblas >=3.9.0,<4.0a0 + - python_abi 3.12.* *_cp312 + - liblapack >=3.9.0,<4.0a0 + - libblas >=3.9.0,<4.0a0 + constrains: + - numpy-base <0a0 + license: BSD-3-Clause + license_family: BSD + purls: + - pkg:pypi/numpy?source=compressed-mapping + size: 8929128 + timestamp: 1783206200235 - pypi: https://files.pythonhosted.org/packages/3b/cd/154ca20c38269e05eff77c1464e6c1da89f50a6390b565e9d82e06bc11e1/nvidia_cublas-13.1.1.3-py3-none-manylinux_2_27_x86_64.whl name: nvidia-cublas version: 13.1.1.3 @@ -2941,6 +3565,18 @@ packages: purls: [] size: 3167099 timestamp: 1775587756857 +- conda: https://conda.anaconda.org/conda-forge/linux-64/openssl-3.6.3-h35e630c_0.conda + sha256: d48f5c22b9897c01e4dff3680f1f57ceb02711ab9c62f74339b080419dfad34b + md5: 79dd2074b5cd5c5c6b2930514a11e22d + depends: + - __glibc >=2.17,<3.0.a0 + - ca-certificates + - libgcc >=14 + license: Apache-2.0 + license_family: Apache + purls: [] + size: 3159683 + timestamp: 1781069855778 - pypi: https://files.pythonhosted.org/packages/23/cd/066e86230ae37ed0be70aae89aabf03ca8d9f39c8aea0dec8029455b5540/opt_einsum-3.4.0-py3-none-any.whl name: opt-einsum version: 3.4.0 @@ -3223,6 +3859,29 @@ packages: - pkg:pypi/pillow?source=hash-mapping size: 1039561 timestamp: 1775060059882 +- conda: https://conda.anaconda.org/conda-forge/linux-64/pillow-12.3.0-py312h50c33e8_0.conda + sha256: 76b2e56c7a903a06be1210d35f35c2a8dcdc57912fda5c96b2e68acfd2b281fe + md5: d749d04e1965315078f29320565c595a + depends: + - python + - libgcc >=14 + - __glibc >=2.17,<3.0.a0 + - libtiff >=4.7.1,<4.8.0a0 + - libxcb >=1.17.0,<2.0a0 + - tk >=8.6.13,<8.7.0a0 + - openjpeg >=2.5.4,<3.0a0 + - zlib-ng >=2.3.3,<2.4.0a0 + - python_abi 3.12.* *_cp312 + - libjpeg-turbo >=3.1.4.1,<4.0a0 + - lcms2 >=2.19.1,<3.0a0 + - libfreetype >=2.14.3 + - libfreetype6 >=2.14.3 + - libwebp-base >=1.6.0,<2.0a0 + license: HPND + purls: + - pkg:pypi/pillow?source=compressed-mapping + size: 1064129 + timestamp: 1782912080163 - conda: https://conda.anaconda.org/conda-forge/linux-64/pixman-0.46.4-h54a6638_1.conda sha256: 43d37bc9ca3b257c5dd7bf76a8426addbdec381f6786ff441dc90b1a49143b6a md5: c01af13bdc553d1a8fbfff6e8db075f0 @@ -3334,6 +3993,11 @@ packages: - pkg:pypi/pycairo?source=hash-mapping size: 119839 timestamp: 1770726341594 +- pypi: https://files.pythonhosted.org/packages/0c/c3/44f3fbbfa403ea2a7c779186dc20772604442dde72947e7d01069cbe98e3/pycparser-3.0-py3-none-any.whl + name: pycparser + version: '3.0' + sha256: b727414169a36b7d524c1c3e31839a521725078d7b2ff038656844266160a992 + requires_python: '>=3.10' - conda: https://conda.anaconda.org/conda-forge/noarch/pycparser-3.0-pyhcf101f3_0.conda sha256: e27e0473fc6723311a0bd48b89b616fa1b996a2f7a2b555338cbbcfb9c640568 md5: 9c5491066224083c41b6d5635ed7107b @@ -3379,6 +4043,22 @@ packages: - pkg:pypi/pydantic-core?source=hash-mapping size: 1895409 timestamp: 1778084226169 +- pypi: https://files.pythonhosted.org/packages/77/c1/6e422f34e569cf8e18df68d1939c81c099d2b61e4f7d9621c8a77560799c/pydantic_settings-2.14.2-py3-none-any.whl + name: pydantic-settings + version: 2.14.2 + sha256: a20c97b37910b6550d5ea50fbcc2d4187defe58cd57070b73863d069419c9440 + requires_dist: + - pydantic>=2.7.0 + - python-dotenv>=0.21.0 + - typing-inspection>=0.4.0 + - boto3>=1.35.0 ; extra == 'aws-secrets-manager' + - types-boto3[secretsmanager] ; extra == 'aws-secrets-manager' + - azure-identity>=1.16.0 ; extra == 'azure-key-vault' + - azure-keyvault-secrets>=4.8.0 ; extra == 'azure-key-vault' + - google-cloud-secret-manager>=2.23.1 ; extra == 'gcp-secret-manager' + - tomli>=2.0.1 ; extra == 'toml' + - pyyaml>=6.0.1 ; extra == 'yaml' + requires_python: '>=3.10' - conda: https://conda.anaconda.org/conda-forge/noarch/pygments-2.20.0-pyhd8ed1ab_0.conda sha256: cf70b2f5ad9ae472b71235e5c8a736c9316df3705746de419b59d442e8348e86 md5: 16c18772b340887160c79a6acc022db0 @@ -3390,6 +4070,14 @@ packages: - pkg:pypi/pygments?source=hash-mapping size: 893031 timestamp: 1774796815820 +- pypi: https://files.pythonhosted.org/packages/a3/5e/ecf12fdb62546d64385c158514e9b2b671f7832108ef2ecd2020ce0af2d1/pyjwt-2.13.0-py3-none-any.whl + name: pyjwt + version: 2.13.0 + sha256: 66adcc2aff09b3f1bbd95fc1e1577df8ac8723c978552fd43304c8a290ac5728 + requires_dist: + - typing-extensions>=4.0 ; python_full_version < '3.11' + - cryptography>=3.4.0 ; extra == 'crypto' + requires_python: '>=3.9' - conda: https://conda.anaconda.org/conda-forge/linux-64/pymatgen-2026.5.4-py312h4f23490_0.conda sha256: f0c69de0163902e54850ec36caa752f16f33132526b6f452ea2ddccbb499939d md5: 387d0b5ebd760649dadb01f7fab43498 @@ -3513,6 +4201,27 @@ packages: - pkg:pypi/pytest?source=hash-mapping size: 299984 timestamp: 1775644472530 +- conda: https://conda.anaconda.org/conda-forge/noarch/pytest-9.1.1-pyhc364b38_2.conda + sha256: 430051d80765207a7d782b2b188230ba1489d35c6e75fd9903f76cb9fda4af16 + md5: 64c98a12c4e23eb238bf66bbecafdf3c + depends: + - colorama + - pygments >=2.7.2 + - python >=3.10 + - iniconfig >=1.0.1 + - packaging >=22 + - pluggy >=1.5,<2 + - tomli >=1 + - exceptiongroup >=1 + - python + constrains: + - pytest-faulthandler >=2 + license: MIT + license_family: MIT + purls: + - pkg:pypi/pytest?source=compressed-mapping + size: 306724 + timestamp: 1782127176429 - conda: https://conda.anaconda.org/conda-forge/linux-64/python-3.12.13-hd63d673_0_cpython.conda sha256: a44655c1c3e1d43ed8704890a91e12afd68130414ea2c0872e154e5633a13d7e md5: 7eccb41177e15cc672e1babe9056018e @@ -3553,6 +4262,23 @@ packages: - pkg:pypi/python-dateutil?source=hash-mapping size: 233310 timestamp: 1751104122689 +- pypi: https://files.pythonhosted.org/packages/0b/d7/1959b9648791274998a9c3526f6d0ec8fd2233e4d4acce81bbae76b44b2a/python_dotenv-1.2.2-py3-none-any.whl + name: python-dotenv + version: 1.2.2 + sha256: 1d8214789a24de455a8b8bd8ae6fe3c6b69a5e3d64aa8a8e5d68e694bbcb285a + requires_dist: + - click>=5.0 ; extra == 'cli' + requires_python: '>=3.10' +- conda: https://conda.anaconda.org/conda-forge/noarch/python-gil-3.12.13-hd8ed1ab_0.conda + sha256: 97327b9509ae3aae28d27217a5d7bd31aff0ab61a02041e9c6f98c11d8a53b29 + md5: 32780d6794b8056b78602103a04e90ef + depends: + - cpython 3.12.13.* + - python_abi * *_cp312 + license: Python-2.0 + purls: [] + size: 46449 + timestamp: 1772728979370 - pypi: https://files.pythonhosted.org/packages/90/cc/bb6395c3f2b6bb739b1d3fc0e71f94e6a1c2e256df496237cbfd13cd74a6/python_hostlist-2.3.0.tar.gz name: python-hostlist version: 2.3.0 @@ -3571,6 +4297,25 @@ packages: - pkg:pypi/librt?source=hash-mapping size: 157857 timestamp: 1778511616936 +- conda: https://conda.anaconda.org/conda-forge/linux-64/python-librt-0.12.0-py312h5253ce2_0.conda + sha256: 77a0592d53fe3664421926c32677f2829278de19d99c90ada80cd75286f34198 + md5: 8ead1974106b7526f4866326654b99ff + depends: + - python + - libgcc >=14 + - __glibc >=2.17,<3.0.a0 + - python_abi 3.12.* *_cp312 + license: MIT + license_family: MIT + purls: + - pkg:pypi/librt?source=hash-mapping + size: 160728 + timestamp: 1782847498143 +- pypi: https://files.pythonhosted.org/packages/e1/04/e8135ebd1ad02c56ec633277529b2602ff99ff634be76cdba5744cf554fd/python_multipart-0.0.32-py3-none-any.whl + name: python-multipart + version: 0.0.32 + sha256: ff6d3f776f16878c894e52e107296ffc890e913c611b1a4ec6c44e2821fe2e23 + requires_python: '>=3.10' - conda: https://conda.anaconda.org/conda-forge/noarch/python_abi-3.12-8_cp312.conda build_number: 8 sha256: 80677180dd3c22deb7426ca89d6203f1c7f1f256f2d5a94dc210f6e758229809 @@ -3661,6 +4406,15 @@ packages: purls: [] size: 345073 timestamp: 1765813471974 +- pypi: https://files.pythonhosted.org/packages/2c/58/ca301544e1fa93ed4f80d724bf5b194f6e4b945841c5bfd555878eea9fcb/referencing-0.37.0-py3-none-any.whl + name: referencing + version: 0.37.0 + sha256: 381329a9f99628c9069361716891d34ad94af76e461dcb0335825aecc7692231 + requires_dist: + - attrs>=22.2.0 + - rpds-py>=0.7.0 + - typing-extensions>=4.4.0 ; python_full_version < '3.13' + requires_python: '>=3.10' - conda: https://conda.anaconda.org/conda-forge/noarch/reportlab-4.5.1-pyhc364b38_0.conda sha256: b9216e69e3a060074835181caa811742036e3c966ea61ec1e31d6c2cbca0992a md5: bcdf1e7f9929961dade936d2c5520ee9 @@ -3735,6 +4489,11 @@ packages: - pkg:pypi/rlpycairo?source=hash-mapping size: 15558 timestamp: 1756864268077 +- pypi: https://files.pythonhosted.org/packages/04/8f/d2f3f532616be4d06c316ef119683e832bd3d41e112bf3a88f4151c95b17/rpds_py-2026.6.3-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl + name: rpds-py + version: 2026.6.3 + sha256: ecabd69db66de867690f9797f2f8fa27ba501bbc24540cbdbdc649cd15888ba6 + requires_python: '>=3.11' - conda: https://conda.anaconda.org/conda-forge/noarch/ruamel.yaml-0.19.1-pyhcf101f3_0.conda sha256: b48bebe297a63ae60f52e50be328262e880702db4d9b4e86731473ada459c2a1 md5: 06ad944772941d5dae1e0d09848d8e49 @@ -3783,6 +4542,22 @@ packages: - pkg:pypi/ruff?source=compressed-mapping size: 9340598 timestamp: 1779388159173 +- conda: https://conda.anaconda.org/conda-forge/linux-64/ruff-0.15.20-h6a952e8_0.conda + noarch: python + sha256: 4c10593eb248ae3b626ebfc2991bd67df96cb98a51816939188576237c54deee + md5: d9b134cef9bc26a9ed9a0fba1eff3356 + depends: + - python + - __glibc >=2.17,<3.0.a0 + - libgcc >=14 + constrains: + - __glibc >=2.17 + license: MIT + license_family: MIT + purls: + - pkg:pypi/ruff?source=compressed-mapping + size: 9342178 + timestamp: 1782428525856 - pypi: https://files.pythonhosted.org/packages/6c/c2/63fdda36c56437eeb44aaf9493c8bcd62ce230ab1598924fc626ffbfa943/scikit_learn-1.9.0-cp312-cp312-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl name: scikit-learn version: 1.9.0 @@ -3870,6 +4645,29 @@ packages: - pkg:pypi/scipy?source=compressed-mapping size: 16828243 timestamp: 1779874781187 +- conda: https://conda.anaconda.org/conda-forge/linux-64/scipy-1.18.0-py312h54fa4ab_0.conda + sha256: c304dfb0bbf0d824d3706623f6437237d7bfc83941bb7b18f80e05abb10ec79e + md5: f8d242c552b0f7f682451ce95879af5e + depends: + - __glibc >=2.17,<3.0.a0 + - libblas >=3.9.0,<4.0a0 + - libcblas >=3.9.0,<4.0a0 + - libgcc >=14 + - libgfortran + - libgfortran5 >=14.3.0 + - liblapack >=3.9.0,<4.0a0 + - libstdcxx >=14 + - numpy <2.7 + - numpy >=1.23,<3 + - numpy >=2.0.0 + - python >=3.12,<3.13.0a0 + - python_abi 3.12.* *_cp312 + license: BSD-3-Clause + license_family: BSD + purls: + - pkg:pypi/scipy?source=compressed-mapping + size: 17104066 + timestamp: 1781912972195 - pypi: https://files.pythonhosted.org/packages/e1/e3/c164c88b2e5ce7b24d667b9bd83589cf4f3520d97cad01534cd3c4f55fdb/setuptools-81.0.0-py3-none-any.whl name: setuptools version: 81.0.0 @@ -4053,6 +4851,36 @@ packages: - pkg:pypi/sqlalchemy?source=compressed-mapping size: 3709206 timestamp: 1779661488554 +- pypi: https://files.pythonhosted.org/packages/78/75/c88d3f5dafd59c791da1ce27650d30bf5b70cbf1cbf01cd00e5f9e360915/sse_starlette-3.4.5-py3-none-any.whl + name: sse-starlette + version: 3.4.5 + sha256: e71bad53323f65573c3864a6c3bd0c1eb6e5f092b2e48082b0c35927d19ca296 + requires_dist: + - starlette>=0.49.1 + - anyio>=4.7.0 + - uvicorn>=0.34.0 ; extra == 'examples' + - fastapi>=0.115.12 ; extra == 'examples' + - pydantic>=2 ; extra == 'examples' + - sqlalchemy[asyncio]>=2.0.41 ; extra == 'examples-db' + - aiosqlite>=0.21.0 ; extra == 'examples-db' + - uvicorn>=0.34.0 ; extra == 'uvicorn' + - granian>=2.3.1 ; extra == 'granian' + - daphne>=4.2.0 ; extra == 'daphne' + requires_python: '>=3.10' +- pypi: https://files.pythonhosted.org/packages/ec/bb/2799cc2ede3ed41131f8975621e7213dfc7ef4acbbaadfa440f32500c370/starlette-1.3.1-py3-none-any.whl + name: starlette + version: 1.3.1 + sha256: c7372aae11c3c3f26a42df7bd626cec2f47d03483d261d369516a615a53714c6 + requires_dist: + - anyio>=3.6.2,<5 + - typing-extensions>=4.10.0 ; python_full_version < '3.13' + - httpx2>=2.0.0 ; extra == 'full' + - httpx>=0.27.0,<0.29.0 ; extra == 'full' + - itsdangerous ; extra == 'full' + - jinja2 ; extra == 'full' + - python-multipart>=0.0.18 ; extra == 'full' + - pyyaml ; extra == 'full' + requires_python: '>=3.10' - pypi: https://files.pythonhosted.org/packages/a2/09/77d55d46fd61b4a135c444fc97158ef34a095e5681d0a6c10b75bf356191/sympy-1.14.0-py3-none-any.whl name: sympy version: 1.14.0 @@ -4395,7 +5223,7 @@ packages: - pypi: ./ name: traincraft version: 0.1.0 - sha256: b3cc69150628c3160b647680cacc8caeaebb9616ad9d40a825b80bfb84b3e3fa + sha256: 14a7624a79a2163b5447dc0967d015d7aa3bde4870879ec10cca2deda71fbf3e requires_dist: - ase>=3.22 - numpy>=1.23 @@ -4410,6 +5238,9 @@ packages: - dscribe ; extra == 'descriptors' - hiphive ; extra == 'sampling' - tblite ; extra == 'semiempirical' + - fastapi>=0.110 ; extra == 'service' + - uvicorn>=0.29 ; extra == 'service' + - mcp>=1.2 ; extra == 'service' - pytest>=7 ; extra == 'dev' - ruff>=0.5 ; extra == 'dev' - mypy>=1.8 ; extra == 'dev' @@ -4460,6 +5291,21 @@ packages: - pkg:pypi/typer?source=hash-mapping size: 184379 timestamp: 1780008156524 +- conda: https://conda.anaconda.org/conda-forge/noarch/typer-0.26.8-pyhcf101f3_0.conda + sha256: a97b824609402c81951640f61abe010bdaa728889c23673ac6c43863cb946c45 + md5: 8bd9c1e0ff3a31a11e21c3f04c2d0f8b + depends: + - annotated-doc >=0.0.2 + - colorama + - python >=3.10 + - rich >=13.8.0 + - shellingham >=1.3.0 + - python + license: MIT AND BSD-3-Clause + purls: + - pkg:pypi/typer?source=compressed-mapping + size: 186572 + timestamp: 1782477870892 - conda: https://conda.anaconda.org/conda-forge/noarch/typing-extensions-4.15.0-h396c80c_0.conda sha256: 7c2df5721c742c2a47b2c8f960e718c930031663ac1174da67c1ed5999f7938c md5: edd329d7d3a4ab45dcf905899a7a6115 @@ -4470,6 +5316,16 @@ packages: purls: [] size: 91383 timestamp: 1756220668932 +- conda: https://conda.anaconda.org/conda-forge/noarch/typing-extensions-4.16.0-h69aa097_0.conda + sha256: b141933ece3518f6d7b75dfb59451e2f26b405a44c18e2518a83e9a02e09315c + md5: c680b5747e8c4c8f23dca0bb7042a8fc + depends: + - typing_extensions ==4.16.0 pyhcf101f3_0 + license: PSF-2.0 + license_family: PSF + purls: [] + size: 94080 + timestamp: 1783002732887 - conda: https://conda.anaconda.org/conda-forge/noarch/typing-inspection-0.4.2-pyhcf101f3_2.conda sha256: 8b90d2f19f9458b8c58a55e1fcdc1d90c1603a847a47654d8a454549413ba60a md5: 53f5409c5cfd6c5a66417d68e3f0a864 @@ -4495,6 +5351,18 @@ packages: - pkg:pypi/typing-extensions?source=hash-mapping size: 51692 timestamp: 1756220668932 +- conda: https://conda.anaconda.org/conda-forge/noarch/typing_extensions-4.16.0-pyhcf101f3_0.conda + sha256: 2d888f90af0686044882c74193ec80a90ec1943145d94a7b1b048958acda1848 + md5: c70ad746c22219b9700931707482992c + depends: + - python >=3.10 + - python + license: PSF-2.0 + license_family: PSF + purls: + - pkg:pypi/typing-extensions?source=compressed-mapping + size: 52631 + timestamp: 1783002732887 - conda: https://conda.anaconda.org/conda-forge/noarch/tzdata-2025c-hc9c84f9_1.conda sha256: 1d30098909076af33a35017eed6f2953af1c769e273a0626a04722ac4acaba3c md5: ad659d0a2b3e47e38d829aa8cad2d610 @@ -4555,6 +5423,22 @@ packages: - pkg:pypi/urllib3?source=hash-mapping size: 103560 timestamp: 1778188657149 +- pypi: https://files.pythonhosted.org/packages/aa/f0/7c228ee10c7ab8fd3a21d06579a6f7c6075c6ce72594a20fb5d2f206ff24/uvicorn-0.50.2-py3-none-any.whl + name: uvicorn + version: 0.50.2 + sha256: 4ae72a385630bcc17a0adb8290f26c993865e0b43a2114c2aab96420172c056a + requires_dist: + - click>=7.0 + - h11>=0.8 + - typing-extensions>=4.0 ; python_full_version < '3.11' + - colorama>=0.4 ; sys_platform == 'win32' and extra == 'standard' + - httptools>=0.8.0 ; extra == 'standard' + - python-dotenv>=0.13 ; extra == 'standard' + - pyyaml>=5.1 ; extra == 'standard' + - uvloop>=0.15.1 ; platform_python_implementation != 'PyPy' and sys_platform != 'cygwin' and sys_platform != 'win32' and extra == 'standard' + - watchfiles>=0.20 ; extra == 'standard' + - websockets>=13.0 ; extra == 'standard' + requires_python: '>=3.10' - pypi: https://files.pythonhosted.org/packages/b5/e8/dbf020b4d98251a9860752a094d09a65e1b436ad181faf929983f697048f/watchdog-6.0.0-py3-none-manylinux2014_x86_64.whl name: watchdog version: 6.0.0 diff --git a/pyproject.toml b/pyproject.toml index 14960ee..ea13b88 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -26,6 +26,7 @@ pysoftk = ["pysoftk"] # separate: polymer builder; install from PyP descriptors = ["dscribe"] sampling = ["hiphive"] semiempirical = ["tblite"] +service = ["fastapi>=0.110", "uvicorn>=0.29", "mcp>=1.2"] dev = ["pytest>=7", "ruff>=0.5", "mypy>=1.8"] docs = ["mkdocs-material>=9.5", "mkdocstrings[python]>=0.25"] @@ -98,6 +99,13 @@ pymatgen = "*" [tool.pixi.feature.descriptors.pypi-dependencies] dscribe = "*" +# service feature (HTTP API + MCP server for agents/workbench) -------------- +[tool.pixi.feature.service.pypi-dependencies] +fastapi = ">=0.110" +uvicorn = ">=0.29" +mcp = ">=1.2" +httpx = "*" # fastapi TestClient transport (tests) + # docs feature (MkDocs + Material + mkdocstrings) -------------------------- [tool.pixi.feature.docs.pypi-dependencies] mkdocs-material = ">=9.5" @@ -117,6 +125,7 @@ default = { solve-group = "default" } dev = { features = ["dev"], solve-group = "default" } science = { features = ["dev", "sampling", "semiempirical", "geometry", "descriptors"] } mace = { features = ["dev", "mace"] } +service = { features = ["dev", "service"] } docs = { features = ["docs"] } # Tasks -------------------------------------------------------------------- diff --git a/skills/traincraft/SKILL.md b/skills/traincraft/SKILL.md index dacc1f8..06bcda1 100644 --- a/skills/traincraft/SKILL.md +++ b/skills/traincraft/SKILL.md @@ -168,3 +168,7 @@ pixi run -e traincraft stage # one stage standalone traincraft runs [outdir] # list all runs + status (default outdir: runs/) traincraft status # per-stage status of one run (live label progress) ``` + +If the `traincraft` MCP server is registered, prefer its tools (`run_status`, +`quality_report`, `validate_config`, `submit_run`) over parsing CLI output — +same operations, structured results. (Setup: `docs/how-to/agent-service.md`.) diff --git a/src/traincraft/cli.py b/src/traincraft/cli.py index bca4394..0a7c0d5 100644 --- a/src/traincraft/cli.py +++ b/src/traincraft/cli.py @@ -171,6 +171,43 @@ def status(run_dir: Path = typer.Argument(..., help="a run directory (e.g. runs/ typer.echo(f" {name:<10} {' '.join(parts)}") +@app.command() +def serve( + outdir: Path = typer.Argument("runs", help="runs root to serve"), + host: str = typer.Option("127.0.0.1", help="bind address (keep it local: no auth)"), + port: int = typer.Option(8137, help="port"), +) -> None: + """Serve the HTTP API over OUTDIR (OpenAPI docs at /docs). + + Needs the service extras (pixi install -e service). Localhost tool with no + auth — don't expose it raw to a network. + """ + try: + import uvicorn + + from .service import create_app + except ImportError: + typer.echo("the HTTP service needs fastapi + uvicorn: pixi install -e service") + raise typer.Exit(code=1) from None + _setup_logging() + uvicorn.run(create_app(outdir), host=host, port=port) + + +@app.command() +def mcp(outdir: Path = typer.Argument("runs", help="runs root the tools operate on")) -> None: + """Run the MCP server on stdio (agent tool access to runs/reports/submission). + + Register with e.g. Claude Code: + claude mcp add traincraft -- pixi run -e service traincraft mcp /path/to/runs + """ + try: + from .service import create_mcp + except ImportError: + typer.echo("the MCP server needs the mcp package: pixi install -e service") + raise typer.Exit(code=1) from None + create_mcp(outdir).run() + + @app.command() def plugins() -> None: """List registered plugins by kind.""" diff --git a/src/traincraft/service/__init__.py b/src/traincraft/service/__init__.py new file mode 100644 index 0000000..f698ced --- /dev/null +++ b/src/traincraft/service/__init__.py @@ -0,0 +1,12 @@ +"""Thin service layer: the same operations as HTTP (FastAPI) and MCP tools. + +``core.py`` holds the dependency-free operations; ``create_app`` / +``create_mcp`` wrap them for the two transports. fastapi/uvicorn/mcp are +optional deps (``pixi install -e service``) imported only inside the factories, +so the core package stays lean. +""" + +from .app import create_app +from .mcp_server import create_mcp + +__all__ = ["create_app", "create_mcp"] diff --git a/src/traincraft/service/app.py b/src/traincraft/service/app.py new file mode 100644 index 0000000..bd086b3 --- /dev/null +++ b/src/traincraft/service/app.py @@ -0,0 +1,91 @@ +"""HTTP API over a runs directory (FastAPI) — the workbench/agent read surface. + +Thin: every endpoint is one call into ``service/core.py``. Start it with +``traincraft serve [OUTDIR]``; interactive docs live at ``/docs`` (OpenAPI). + +Security model: **localhost tool, no auth** — it exposes run results and can +start pipelines from server-side config paths. Bind it to 127.0.0.1 (the +default) or put a real gateway in front; never expose it raw to a network. +""" + +# NOTE: no `from __future__ import annotations` here — FastAPI must resolve +# the request-model annotations at runtime, and stringified locals break that. +from pathlib import Path + +from pydantic import BaseModel + +from .. import __version__ +from . import core + + +class ConfigText(BaseModel): + toml: str + + +class Submission(BaseModel): + config_path: str + force: bool = False + + +def create_app(outdir: "str | Path" = "runs"): + try: + from fastapi import FastAPI, HTTPException + except ImportError as exc: # pragma: no cover + raise ImportError( + "the HTTP service needs fastapi — install with: pixi install -e service" + ) from exc + + outdir = Path(outdir) + app = FastAPI( + title="TrainCraft", + version=__version__, + description=f"Run state, quality reports and pipeline submission over `{outdir}`.", + ) + + def _found(fn, *args): + try: + return fn(*args) + except FileNotFoundError as exc: + raise HTTPException(status_code=404, detail=str(exc)) from exc + + @app.get("/runs") + def runs() -> list[dict]: + """All runs with their current status (index refreshed lazily).""" + return core.list_runs(outdir) + + @app.get("/runs/{name}") + def run_detail(name: str) -> dict: + """Per-stage status of one run, from its event log.""" + return _found(core.get_run, outdir, name) + + @app.get("/runs/{name}/events") + def run_events(name: str) -> list[dict]: + """The raw event log (oldest first).""" + return _found(core.get_events, outdir, name) + + @app.get("/runs/{name}/report") + def quality_report(name: str) -> dict: + """The validation quality report (metrics, threshold checks, passed).""" + return _found(core.get_report, outdir, name) + + @app.get("/runs/{name}/manifest/{stage}") + def stage_manifest(name: str, stage: str) -> dict: + """A stage's manifest.json (label, train).""" + return _found(core.get_manifest, outdir, name, stage) + + @app.post("/config/validate") + def validate_config(body: ConfigText) -> dict: + """Validate TOML config text (same check as `traincraft validate`).""" + return core.validate_config_text(body.toml) + + @app.post("/runs") + def submit(body: Submission) -> dict: + """Start the pipeline for a server-side config file; returns immediately.""" + try: + return core.submit_config(body.config_path, force=body.force) + except FileNotFoundError as exc: + raise HTTPException(status_code=404, detail=str(exc)) from exc + except Exception as exc: # bad config, unloadable sections, … + raise HTTPException(status_code=422, detail=str(exc)) from exc + + return app diff --git a/src/traincraft/service/core.py b/src/traincraft/service/core.py new file mode 100644 index 0000000..7adf436 --- /dev/null +++ b/src/traincraft/service/core.py @@ -0,0 +1,137 @@ +"""Shared service operations — plain functions over the library API. + +Both the HTTP app (``service/app.py``) and the MCP server +(``service/mcp_server.py``) are thin wrappers around these functions, so the +two surfaces expose exactly the same capabilities and cannot drift. Everything +here is dependency-free (no fastapi/mcp imports) and returns JSON-able dicts. + +The service is **local-first**: it reads the same on-disk state the CLI reads +(``events.jsonl`` per run + stage manifests), so it needs no daemon or database +beside the runs directory itself. +""" + +from __future__ import annotations + +import json +import subprocess +import sys +from pathlib import Path + +from ..config import load_config, loads_config +from ..orchestration import submit_slurm +from ..orchestration.stages import enabled_stages, workspace_for +from ..state import RunIndex, run_status +from ..validation import REPORT_NAME + +_MANIFESTS = { + "label": ("labeled_dft", "manifest.json"), + "train": ("model", "manifest.json"), +} + + +def _run_dir(outdir: str | Path, name: str) -> Path: + """Resolve a run name below ``outdir``, refusing path escapes.""" + if not name or "/" in name or "\\" in name or name in (".", ".."): + raise FileNotFoundError(f"not a run name: {name!r}") + run_dir = Path(outdir) / name + if not run_dir.is_dir(): + raise FileNotFoundError(f"no run named {name!r} under {outdir}") + return run_dir + + +def list_runs(outdir: str | Path) -> list[dict]: + """Every run under ``outdir`` (index refreshed first), newest first.""" + index = RunIndex(outdir) + index.refresh() + return [ + {k: st.get(k) for k in ("name", "status", "last_stage", "engine", "started", "updated")} + for st in index.runs() + ] + + +def get_run(outdir: str | Path, name: str) -> dict: + """Full per-stage status of one run, straight from its event log.""" + return run_status(_run_dir(outdir, name)) + + +def get_events(outdir: str | Path, name: str) -> list[dict]: + """The raw event log of one run (oldest first).""" + from ..state import read_events + + return read_events(_run_dir(outdir, name)) + + +def get_report(outdir: str | Path, name: str) -> dict: + """The run's validation ``quality_report.json`` (metrics, checks, passed).""" + path = _run_dir(outdir, name) / "validation" / REPORT_NAME + if not path.exists(): + raise FileNotFoundError(f"run {name!r} has no quality report (no validate stage yet)") + return json.loads(path.read_text()) + + +def get_manifest(outdir: str | Path, name: str, stage: str) -> dict: + """A stage's ``manifest.json`` (stages that write one: label, train).""" + if stage not in _MANIFESTS: + raise FileNotFoundError( + f"stage {stage!r} writes no manifest; choose from {sorted(_MANIFESTS)}" + ) + sub, fname = _MANIFESTS[stage] + path = _run_dir(outdir, name) / sub / fname + if not path.exists(): + raise FileNotFoundError(f"run {name!r} has no {stage} manifest yet") + return json.loads(path.read_text()) + + +def validate_config_text(text: str) -> dict: + """Validate a TOML config string; never raises. + + Returns ``{"valid": bool, "name", "stages", "errors"}`` — the same check as + ``traincraft validate``, but on config *text* so callers need no file. + """ + try: + cfg = loads_config(text) + except Exception as exc: + return {"valid": False, "name": None, "stages": [], "errors": str(exc)} + return { + "valid": True, + "name": cfg.run.name, + "stages": enabled_stages(cfg), + "errors": None, + } + + +def submit_config(config_path: str | Path, *, force: bool = False) -> dict: + """Start the pipeline for a config file; return immediately. + + Slurm configs are submitted as dependency-chained jobs; anything else runs + as a **detached local process** (output to ``/local.log``). Either way + progress is observable through the run's event log (``get_run``). + """ + config_path = Path(config_path).resolve() + cfg = load_config(config_path) + ws = workspace_for(cfg) + + if cfg.orchestration is not None and cfg.orchestration.engine == "slurm": + jobs = submit_slurm(cfg, str(config_path)) + return { + "run": cfg.run.name, + "dir": str(ws.root), + "engine": "slurm", + "jobs": {j.stage: j.job_id for j in jobs}, + } + + cmd = [sys.executable, "-m", "traincraft.cli", "run", str(config_path)] + if force: + cmd.append("--force") + log = ws.root / "local.log" + with log.open("ab") as fh: + proc = subprocess.Popen( + cmd, stdout=fh, stderr=subprocess.STDOUT, start_new_session=True + ) + return { + "run": cfg.run.name, + "dir": str(ws.root), + "engine": "local", + "pid": proc.pid, + "log": str(log), + } diff --git a/src/traincraft/service/mcp_server.py b/src/traincraft/service/mcp_server.py new file mode 100644 index 0000000..c340434 --- /dev/null +++ b/src/traincraft/service/mcp_server.py @@ -0,0 +1,82 @@ +"""MCP server — the same operations as the HTTP app, as agent tools. + +Runs on stdio via ``traincraft mcp [OUTDIR]``. Register with an MCP client, +e.g. Claude Code: + + claude mcp add traincraft -- pixi run -e service traincraft mcp /path/to/runs + +Tool docstrings are the agent's only manual — they state what each tool +returns *and* how to act on it (e.g. never call a model good without reading +its quality report). +""" + +from __future__ import annotations + +from pathlib import Path + +from . import core + + +def create_mcp(outdir: str | Path = "runs"): + try: + from mcp.server.fastmcp import FastMCP + except ImportError as exc: # pragma: no cover + raise ImportError( + "the MCP server needs the mcp package — install with: pixi install -e service" + ) from exc + + outdir = Path(outdir) + server = FastMCP( + "traincraft", + instructions=( + "TrainCraft generates MLIP training datasets and fine-tunes MACE " + f"models. These tools operate on the runs directory `{outdir}`. " + "Judge a trained model ONLY by its quality report " + "(quality_report tool) — never from training logs alone." + ), + ) + + @server.tool() + def list_runs() -> list[dict]: + """List every TrainCraft run with its status (running/completed/failed/…), + last active stage, engine and timestamps. Start here to find a run.""" + return core.list_runs(outdir) + + @server.tool() + def run_status(name: str) -> dict: + """Per-stage status of one run: state (pending/running/done/cached/failed), + frame counts, wall times, errors, and live labeling progress. Use this to + answer 'where is my run?' — do not parse logs.""" + return core.get_run(outdir, name) + + @server.tool() + def quality_report(name: str) -> dict: + """The run's validation quality report: RMSE/MAE per property, + per-element force errors, threshold checks and the overall pass/fail. + Read this before making ANY claim about a trained model's quality, and + report the metrics + verdict to the user.""" + return core.get_report(outdir, name) + + @server.tool() + def stage_manifest(name: str, stage: str) -> dict: + """A stage's manifest.json. stage='label' → level of theory + counts + (n_attempted/n_failed/n_reused) + per-frame errors; stage='train' → the + exact rendered training command, heads, and split sizes.""" + return core.get_manifest(outdir, name, stage) + + @server.tool() + def validate_config(toml_text: str) -> dict: + """Validate TrainCraft TOML config text without running anything. + Returns {valid, name, stages, errors}. ALWAYS validate before submitting; + fix every error rather than guessing at field names.""" + return core.validate_config_text(toml_text) + + @server.tool() + def submit_run(config_path: str, force: bool = False) -> dict: + """Start the pipeline for a config FILE PATH (Slurm if configured, else a + detached local process) and return immediately. Confirm with the user + before submitting anything expensive (DFT labeling, MACE training). + Track progress afterwards with run_status.""" + return core.submit_config(config_path, force=force) + + return server diff --git a/tests/test_service.py b/tests/test_service.py new file mode 100644 index 0000000..7d09a5a --- /dev/null +++ b/tests/test_service.py @@ -0,0 +1,195 @@ +"""Service layer: shared core operations + the FastAPI and MCP wrappers. + +Core tests run in every env; the HTTP/MCP tests skip unless the `service` +extras are installed (run them with `pixi run -e service test`). +""" + +from __future__ import annotations + +import pytest + +from traincraft import run_pipeline +from traincraft.config.models import ( + CrystalBuilder, + EmtCalc, + GeometryConfig, + LabelingConfig, + MdSampling, + RunConfig, + SelectionConfig, + TrainCraftConfig, + ValidationConfig, +) +from traincraft.service import core + +_CONFIG_TOML = """ +[run] +name = "svc" +seed = 1 +outdir = "{outdir}" + +[geometry.builder] +type = "crystal" +name = "Cu" +crystalstructure = "fcc" +a = 3.6 +cubic = true +supercell = [2, 2, 2] + +[calculator] +type = "emt" + +[sampling] +type = "md" +temperature = 300.0 +steps = 30 +interval = 10 + +[selection] +budget = 2 + +[labeling.calculator] +type = "emt" + +[validation.calculator] +type = "emt" + +[validation.thresholds] +forces_rmse = 0.05 +""" + + +@pytest.fixture(scope="module") +def runs_root(tmp_path_factory): + """One completed run (with validation) under a shared outdir.""" + outdir = tmp_path_factory.mktemp("runs") + cfg = TrainCraftConfig( + run=RunConfig(name="svc", outdir=str(outdir), seed=1), + geometry=GeometryConfig( + builder=CrystalBuilder( + name="Cu", crystalstructure="fcc", a=3.6, cubic=True, supercell=(2, 2, 2) + ) + ), + calculator=EmtCalc(), + sampling=MdSampling(temperature=300.0, steps=30, interval=10), + selection=SelectionConfig(budget=2), + labeling=LabelingConfig(calculator=EmtCalc()), + validation=ValidationConfig( + calculator=EmtCalc(), thresholds={"forces_rmse": 0.05} + ), + ) + run_pipeline(cfg) + return outdir + + +# --- core operations --------------------------------------------------------- + +def test_list_runs(runs_root): + runs = core.list_runs(runs_root) + assert [r["name"] for r in runs] == ["svc"] + assert runs[0]["status"] == "completed" + + +def test_get_run_and_events(runs_root): + st = core.get_run(runs_root, "svc") + assert st["status"] == "completed" + assert st["stages"]["validate"]["passed"] is True + events = core.get_events(runs_root, "svc") + assert events[0]["stage"] == "run" + + +def test_get_report(runs_root): + report = core.get_report(runs_root, "svc") + assert report["passed"] is True + assert "forces_rmse" in report["metrics"] + + +def test_get_manifest(runs_root): + manifest = core.get_manifest(runs_root, "svc", "label") + assert manifest["n_failed"] == 0 + with pytest.raises(FileNotFoundError, match="no manifest"): + core.get_manifest(runs_root, "svc", "geometry") + + +def test_unknown_run_raises(runs_root): + with pytest.raises(FileNotFoundError): + core.get_run(runs_root, "nope") + + +def test_run_name_cannot_escape_outdir(runs_root): + for name in ("../svc", "a/b", "..", ""): + with pytest.raises(FileNotFoundError): + core.get_run(runs_root, name) + + +def test_validate_config_text(tmp_path): + result = core.validate_config_text(_CONFIG_TOML.format(outdir=tmp_path)) + assert result["valid"] is True + assert result["name"] == "svc" + assert result["stages"] == ["geometry", "sample", "select", "label", "validate"] + + bad = core.validate_config_text("[geometry.builder]\ntype = 'no_such_builder'\n") + assert bad["valid"] is False + assert "no_such_builder" in bad["errors"] + + +def test_submit_config_local_detaches(tmp_path, monkeypatch): + calls = {} + + class _Proc: + pid = 4242 + + def _popen(cmd, **kwargs): + calls["cmd"] = cmd + calls["kwargs"] = kwargs + return _Proc() + + monkeypatch.setattr(core.subprocess, "Popen", _popen) + config = tmp_path / "svc.toml" + config.write_text(_CONFIG_TOML.format(outdir=tmp_path / "runs")) + + out = core.submit_config(config, force=True) + assert out["engine"] == "local" + assert out["pid"] == 4242 + assert calls["cmd"][-3:] == ["run", str(config), "--force"] + assert calls["kwargs"]["start_new_session"] is True + + +# --- HTTP app (needs fastapi) ------------------------------------------------ + +def _client(runs_root): + pytest.importorskip("fastapi") + from fastapi.testclient import TestClient + + from traincraft.service import create_app + + return TestClient(create_app(runs_root)) + + +def test_http_endpoints(runs_root): + client = _client(runs_root) + assert client.get("/runs").json()[0]["name"] == "svc" + assert client.get("/runs/svc").json()["status"] == "completed" + assert client.get("/runs/svc/report").json()["passed"] is True + assert client.get("/runs/svc/manifest/label").json()["n_failed"] == 0 + assert client.get("/runs/nope").status_code == 404 + assert client.get("/runs/svc/manifest/geometry").status_code == 404 + + ok = client.post("/config/validate", json={"toml": "[run]\nname = 'x'\n"}) + assert ok.json()["valid"] is True + + +# --- MCP server (needs mcp) -------------------------------------------------- + +def test_mcp_tools_mirror_core(runs_root): + pytest.importorskip("mcp") + import asyncio + + from traincraft.service import create_mcp + + server = create_mcp(runs_root) + tools = {t.name for t in asyncio.run(server.list_tools())} + assert tools == { + "list_runs", "run_status", "quality_report", + "stage_manifest", "validate_config", "submit_run", + } From 9a32536d57ae2a047ae9c59429f467fa506937e8 Mon Sep 17 00:00:00 2001 From: David Abbasi Perez Date: Tue, 7 Jul 2026 23:23:49 +0200 Subject: [PATCH 07/15] polish(cli): rich help with workflow-grouped command panels and per-command examples, colored runs/status output, --json for the inspect commands Co-Authored-By: Claude Fable 5 Claude-Session: https://claude.ai/code/session_01V6f4Z4uLdysBeehYfbQ56k --- docs/reference/cli.md | 10 +- skills/traincraft/SKILL.md | 6 +- src/traincraft/cli.py | 364 +++++++++++++++++++++++++++---------- 3 files changed, 275 insertions(+), 105 deletions(-) diff --git a/docs/reference/cli.md b/docs/reference/cli.md index c666338..728745f 100644 --- a/docs/reference/cli.md +++ b/docs/reference/cli.md @@ -6,6 +6,12 @@ The `traincraft` CLI is installed as a console script when you install the packa traincraft --help ``` +`--help` groups the commands by workflow — **author & check configs** (`new`, +`validate`, `plugins`) → **run the pipeline** (`run`, `stage`, `submit`) → +**inspect runs** (`runs`, `status`) → **agents & services** (`serve`, `mcp`) — +and every command's own `--help` carries a usage example. The inspect commands +take `--json` for scripting. + --- ## `traincraft run` @@ -128,7 +134,7 @@ The GPU stages (`sample`, `train`, `validate`) run in `traincraft-mlip.sif` with List every run under an output directory with its current status. ```bash -traincraft runs [OUTDIR] # default: runs/ +traincraft runs [OUTDIR] [--json] # default: runs/ ``` ``` @@ -152,7 +158,7 @@ is why the whole scheme is safe on Lustre/NFS. Per-stage status of a single run, read from its `events.jsonl`. ```bash -traincraft status RUN_DIR # e.g. traincraft status runs/cnt_water_600K +traincraft status RUN_DIR [--json] # e.g. traincraft status runs/cnt_water_600K ``` ``` diff --git a/skills/traincraft/SKILL.md b/skills/traincraft/SKILL.md index 06bcda1..278ab52 100644 --- a/skills/traincraft/SKILL.md +++ b/skills/traincraft/SKILL.md @@ -165,10 +165,12 @@ traincraft validate # validate + show resolved stages pixi run -e traincraft run # run the pipeline pixi run -e traincraft stage # one stage standalone # (geometry|sample|select|label|dataset|train|validate) -traincraft runs [outdir] # list all runs + status (default outdir: runs/) -traincraft status # per-stage status of one run (live label progress) +traincraft runs [outdir] [--json] # list all runs + status (default outdir: runs/) +traincraft status [--json] # per-stage status of one run (live label progress) ``` +Prefer `--json` on the inspect commands when you need to parse the output. + If the `traincraft` MCP server is registered, prefer its tools (`run_status`, `quality_report`, `validate_config`, `submit_run`) over parsing CLI output — same operations, structured results. (Setup: `docs/how-to/agent-service.md`.) diff --git a/src/traincraft/cli.py b/src/traincraft/cli.py index 0a7c0d5..0f3e9e6 100644 --- a/src/traincraft/cli.py +++ b/src/traincraft/cli.py @@ -1,22 +1,69 @@ -"""TrainCraft command-line interface (thin shell over the public API).""" +"""TrainCraft command-line interface (thin shell over the public API). + +Help text uses typer's rich mode: commands are grouped into workflow panels +(author → run → inspect → serve) and each command carries a usage example. +Literal TOML section names must be written ``\\[section]`` in help strings or +rich eats them as markup tags. +""" from __future__ import annotations +import json import logging from pathlib import Path import typer +from rich.console import Console +from rich.table import Table from .config import dump_starter_config, load_config from .core import available from .orchestration import STAGE_ORDER, run_pipeline, run_stage, submit_slurm from .state import RunIndex, run_status +_AUTHOR = "1 · Author & check configs" +_RUN = "2 · Run the pipeline" +_INSPECT = "3 · Inspect runs" +_SERVE = "4 · Agents & services" + app = typer.Typer( add_completion=False, - help="TrainCraft: modular MLIP dataset generation & active learning.", + rich_markup_mode="rich", + help="""[b]TrainCraft[/] — modular MLIP dataset generation & MACE-centric active learning. + +One TOML config drives the whole pipeline +[cyan]geometry → sample → select → label → dataset → train → validate[/] +and stages cache their artifacts: rerunning a config only redoes what changed. + +[b]A typical session[/] + +\b + [cyan]traincraft new my_run.toml[/] start from a commented template + [cyan]traincraft validate my_run.toml[/] catch errors before spending compute + [cyan]traincraft run my_run.toml[/] run it (local, or Slurm if configured) + [cyan]traincraft status runs/my_run[/] where is it? what failed? + +Docs & config schema: [link]https://basillicus.github.io/traincraft[/link] +""", ) +_console = Console() + +_STATUS_STYLE = { + "completed": "green", + "running": "yellow", + "failed": "bold red", + "partial": "cyan", + "empty": "dim", +} +_STAGE_STYLE = { + "done": "green", + "cached": "dim green", + "running": "yellow", + "failed": "bold red", + "pending": "dim", +} + def _setup_logging() -> None: logging.basicConfig( @@ -24,18 +71,98 @@ def _setup_logging() -> None: ) -@app.command() +# --- 1 · author & check ------------------------------------------------------ + +@app.command(rich_help_panel=_AUTHOR) +def new( + path: Path = typer.Argument(..., help="where to write the .toml (must not exist)"), +) -> None: + """Write a commented starter config to PATH. + + The template covers every major section with sane defaults — delete what + you don't need (only the sections present in the file run). + + [b]Example[/] + + \b + [cyan]traincraft new my_run.toml && $EDITOR my_run.toml[/] + """ + if path.exists(): + typer.echo(f"refusing to overwrite existing file: {path}") + raise typer.Exit(code=1) + path.write_text(dump_starter_config()) + typer.echo(f"wrote starter config: {path}") + + +@app.command(rich_help_panel=_AUTHOR) +def validate( + config: Path = typer.Argument(..., exists=True, readable=True, help="the .toml to check"), +) -> None: + """Validate CONFIG and show which stages it will run — costs nothing. + + Catches typos, wrong field names and type errors with pydantic's full + message. Always run this before anything expensive. + + [b]Example[/] + + \b + [cyan]traincraft validate my_run.toml[/] + OK: config is valid + run: my_run + stages: geometry, calculator, sampling, selection, labeling + """ + cfg = load_config(config) + stages = [ + name + for name in ( + "geometry", "calculator", "sampling", "selection", + "labeling", "dataset", "training", "validation", + ) + if getattr(cfg, name) is not None + ] + _console.print("[green]OK[/]: config is valid") + typer.echo(f" run: {cfg.run.name}") + typer.echo(f" stages: {', '.join(stages) or '(none)'}") + + +@app.command(rich_help_panel=_AUTHOR) +def plugins() -> None: + """List every registered plugin, grouped by kind. + + What's listed depends on the active environment — e.g. [cyan]smiles[/] and + [cyan]surface_packing[/] appear only in the science env (RDKit + Packmol), + [cyan]mace[/] only where mace-torch is installed. + """ + for kind in ( + "source", "builder", "transform", "calculator", "sampler", "selector", "trainer", + ): + names = ", ".join(available(kind)) or "(none)" + _console.print(f"[b cyan]{kind:<11}[/] {names}") + + +# --- 2 · run ------------------------------------------------------------------ + +@app.command(rich_help_panel=_RUN) def run( - config: Path = typer.Argument(..., exists=True, readable=True), + config: Path = typer.Argument(..., exists=True, readable=True, help="the .toml to run"), force: bool = typer.Option( False, "--force", "-f", help="recompute every stage, ignoring cached artifacts (a clean slate)", ), ) -> None: - """Run the workflow in CONFIG. Routes to Slurm if [orchestration].engine="slurm". + """Run the whole workflow in CONFIG (the main command). + + Stages are cached: a stage reruns only if its own config — or anything + upstream of it — changed since the last run, so editing one section and + rerunning recomputes exactly the affected stages. Routes to Slurm instead + when the config sets \\[orchestration] [cyan]engine = "slurm"[/]. - Stages are cached: a stage reruns only if its config (or an upstream stage) - changed since the last run. Pass --force to recompute everything regardless. + [b]Examples[/] + + \b + [cyan]traincraft run my_run.toml[/] run / resume + [cyan]traincraft run my_run.toml --force[/] recompute everything + [cyan]pixi run -e mace traincraft run t.toml[/] with MACE on the path """ _setup_logging() cfg = load_config(config) @@ -52,12 +179,44 @@ def run( typer.echo(f" {key}: {value}") -@app.command() +@app.command(rich_help_panel=_RUN) +def stage( + name: str = typer.Argument(..., help=f"one of: {', '.join(STAGE_ORDER)}"), + config: Path = typer.Argument(..., exists=True, readable=True, help="the .toml to use"), + force: bool = typer.Option(False, "--force", help="recompute even if the artifact exists"), +) -> None: + """Run one pipeline stage standalone; upstream artifacts come from disk. + + This is what the Slurm executor dispatches as separate jobs — and how you + train or validate against artifacts you already have. + + [b]Example — train on an existing dataset[/] + + \b + [cyan]pixi run -e mace traincraft stage train my_run.toml[/] + """ + _setup_logging() + cfg = load_config(config) + frames = run_stage(name, cfg, force=force) + typer.echo(f"stage '{name}': {len(frames)} frames") + + +@app.command(rich_help_panel=_RUN) def submit( - config: Path = typer.Argument(..., exists=True, readable=True), + config: Path = typer.Argument(..., exists=True, readable=True, help="the .toml to submit"), dry_run: bool = typer.Option(False, "--dry-run", help="write sbatch scripts but don't submit"), ) -> None: - """Render + submit the workflow as dependency-chained Slurm jobs (Apptainer).""" + """Render + submit CONFIG as dependency-chained Slurm jobs (Apptainer). + + Needs an \\[orchestration.slurm] section. Use [cyan]--dry-run[/] to inspect + the rendered sbatch scripts (under [cyan]runs//slurm/[/]) before + spending queue time. + + [b]Example[/] + + \b + [cyan]traincraft submit my_run.toml --dry-run[/] + """ _setup_logging() cfg = load_config(config) if cfg.orchestration is None or cfg.orchestration.slurm is None: @@ -72,56 +231,24 @@ def submit( typer.echo(f" {job.stage}{dep}: {job.script}{jid}") -@app.command() -def stage( - name: str = typer.Argument(..., help=f"one of: {', '.join(STAGE_ORDER)}"), - config: Path = typer.Argument(..., exists=True, readable=True), - force: bool = typer.Option(False, "--force", help="recompute even if the artifact exists"), -) -> None: - """Run a single pipeline stage standalone (reads/writes workspace artifacts). - - This is what the Slurm executor dispatches as separate jobs; each stage picks - up the previous stage's artifact from the run workspace. - """ - _setup_logging() - cfg = load_config(config) - frames = run_stage(name, cfg, force=force) - typer.echo(f"stage '{name}': {len(frames)} frames") - - -@app.command() -def validate(config: Path = typer.Argument(..., exists=True, readable=True)) -> None: - """Validate CONFIG and print the resolved stages.""" - cfg = load_config(config) - stages = [ - name - for name in ( - "geometry", "calculator", "sampling", "selection", - "labeling", "dataset", "training", "validation", - ) - if getattr(cfg, name) is not None - ] - typer.echo("OK: config is valid") - typer.echo(f" run: {cfg.run.name}") - typer.echo(f" stages: {', '.join(stages) or '(none)'}") - +# --- 3 · inspect --------------------------------------------------------------- -@app.command() -def new(path: Path = typer.Argument(...)) -> None: - """Write a starter config to PATH.""" - if path.exists(): - typer.echo(f"refusing to overwrite existing file: {path}") - raise typer.Exit(code=1) - path.write_text(dump_starter_config()) - typer.echo(f"wrote starter config: {path}") +@app.command(rich_help_panel=_INSPECT) +def runs( + outdir: Path = typer.Argument("runs", help="runs root (the \\[run] outdir)"), + as_json: bool = typer.Option(False, "--json", help="machine-readable output"), +) -> None: + """List all runs under OUTDIR with their current status. + Backed by the SQLite index ([cyan]/index.db[/]), refreshed lazily + from each run's event log — fast even with thousands of runs. The index is + a disposable cache: deleting it is always safe. -@app.command() -def runs(outdir: Path = typer.Argument("runs", help="runs root (the [run].outdir)")) -> None: - """List all runs under OUTDIR with their current status. + [b]Example[/] - Backed by the SQLite index (/index.db), refreshed lazily from each - run's events.jsonl. The index is a cache: deleting it is always safe. + \b + [cyan]traincraft runs[/] the default runs/ directory + [cyan]traincraft runs --json | jq[/] for scripts """ if not outdir.is_dir(): typer.echo(f"no such directory: {outdir}") @@ -129,49 +256,87 @@ def runs(outdir: Path = typer.Argument("runs", help="runs root (the [run].outdir index = RunIndex(outdir) index.refresh() entries = index.runs() + if as_json: + typer.echo(json.dumps(entries, indent=2)) + return if not entries: typer.echo(f"no runs found under {outdir}") return - typer.echo(f"{'RUN':<24} {'STATUS':<10} {'LAST STAGE':<12} {'UPDATED':<20} ENGINE") + table = Table(box=None, header_style="bold") + for col in ("RUN", "STATUS", "LAST STAGE", "UPDATED", "ENGINE"): + table.add_column(col) for st in entries: - typer.echo( - f"{st['name']:<24} {st['status']:<10} {st['last_stage'] or '-':<12} " - f"{st['updated'] or '-':<20} {st['engine'] or '-'}" + table.add_row( + st["name"], + f"[{_STATUS_STYLE.get(st['status'], 'white')}]{st['status']}[/]", + st["last_stage"] or "-", + st["updated"] or "-", + st["engine"] or "-", ) + _console.print(table) + + +@app.command(rich_help_panel=_INSPECT) +def status( + run_dir: Path = typer.Argument(..., help="a run directory (e.g. runs/)"), + as_json: bool = typer.Option(False, "--json", help="machine-readable output"), +) -> None: + """Per-stage status of one run: state, counts, timings, errors. + + Reads the run's event log ([cyan]events.jsonl[/]) — works from any login + node, no daemon needed. While labeling runs, live frame counts are shown + from [cyan]receipts.jsonl[/]. + [b]Example[/] -@app.command() -def status(run_dir: Path = typer.Argument(..., help="a run directory (e.g. runs/)")) -> None: - """Per-stage status of one run, read from its events.jsonl.""" + \b + [cyan]traincraft status runs/my_run[/] + run: my_run \\[running] engine=slurm + geometry done 1 frames 0.4s + label running 231 done / 4 failed so far + """ st = run_status(run_dir) if st["status"] == "empty": typer.echo(f"no run state recorded in {run_dir} (no events.jsonl)") raise typer.Exit(code=1) - typer.echo(f"run: {st['name']} [{st['status']}] engine={st['engine'] or '-'}") + if as_json: + typer.echo(json.dumps(st, indent=2)) + return + style = _STATUS_STYLE.get(st["status"], "white") + _console.print( + f"run: [b]{st['name']}[/] [{style}]\\[{st['status']}][/] engine={st['engine'] or '-'}" + ) names = st["planned"] or [n for n in STAGE_ORDER if n in st["stages"]] for name in names: stage = st["stages"].get(name) - if stage is None: - typer.echo(f" {name:<10} pending") - continue - parts = [stage["state"]] - if "n_frames" in stage: - parts.append(f"{stage['n_frames']} frames") - if stage.get("n_failed"): - parts.append(f"{stage['n_failed']} failed") - if "passed" in stage: - parts.append({True: "passed", False: "FAILED", None: "no thresholds"}[stage["passed"]]) - if "wall_seconds" in stage: - parts.append(f"{stage['wall_seconds']}s") - if "progress" in stage: - p = stage["progress"] - parts.append(f"{p['n_done']} done / {p['n_failed']} failed so far") - if "error" in stage: - parts.append(stage["error"]) - typer.echo(f" {name:<10} {' '.join(parts)}") - - -@app.command() + state = stage["state"] if stage else "pending" + parts: list[str] = [] + if stage: + if "n_frames" in stage: + parts.append(f"{stage['n_frames']} frames") + if stage.get("n_failed"): + parts.append(f"{stage['n_failed']} failed") + if "passed" in stage: + parts.append( + {True: "passed", False: "FAILED", None: "no thresholds"}[stage["passed"]] + ) + if "wall_seconds" in stage: + parts.append(f"{stage['wall_seconds']}s") + if "progress" in stage: + p = stage["progress"] + parts.append(f"{p['n_done']} done / {p['n_failed']} failed so far") + if "error" in stage: + parts.append(stage["error"]) + _console.print( + f" {name:<10} [{_STAGE_STYLE.get(state, 'white')}]{state}[/] " + + " ".join(parts), + highlight=False, + ) + + +# --- 4 · agents & services ----------------------------------------------------- + +@app.command(rich_help_panel=_SERVE) def serve( outdir: Path = typer.Argument("runs", help="runs root to serve"), host: str = typer.Option("127.0.0.1", help="bind address (keep it local: no auth)"), @@ -179,8 +344,10 @@ def serve( ) -> None: """Serve the HTTP API over OUTDIR (OpenAPI docs at /docs). - Needs the service extras (pixi install -e service). Localhost tool with no - auth — don't expose it raw to a network. + Same operations as the CLI's inspect commands plus config validation and + submission — for dashboards and scripts. Needs the service extras + ([cyan]pixi install -e service[/]). [b red]No auth[/] — keep it on + localhost or behind a real gateway. """ try: import uvicorn @@ -193,12 +360,16 @@ def serve( uvicorn.run(create_app(outdir), host=host, port=port) -@app.command() -def mcp(outdir: Path = typer.Argument("runs", help="runs root the tools operate on")) -> None: - """Run the MCP server on stdio (agent tool access to runs/reports/submission). +@app.command(rich_help_panel=_SERVE) +def mcp( + outdir: Path = typer.Argument("runs", help="runs root the tools operate on"), +) -> None: + """Run the MCP server on stdio — the same operations as agent tools. - Register with e.g. Claude Code: - claude mcp add traincraft -- pixi run -e service traincraft mcp /path/to/runs + [b]Register with Claude Code[/] + + \b + [cyan]claude mcp add traincraft -- pixi run -e service traincraft mcp /abs/path/to/runs[/] """ try: from .service import create_mcp @@ -208,14 +379,5 @@ def mcp(outdir: Path = typer.Argument("runs", help="runs root the tools operate create_mcp(outdir).run() -@app.command() -def plugins() -> None: - """List registered plugins by kind.""" - for kind in ( - "source", "builder", "transform", "calculator", "sampler", "selector", "trainer", - ): - typer.echo(f"{kind}: {', '.join(available(kind)) or '(none)'}") - - if __name__ == "__main__": # pragma: no cover app() From 9e9daadccd52978763835700a57269a2eef8c189 Mon Sep 17 00:00:00 2001 From: David Abbasi Perez Date: Fri, 10 Jul 2026 22:06:41 +0200 Subject: [PATCH 08/15] =?UTF-8?q?feat(geometry):=20multi-structure=20spine?= =?UTF-8?q?=20=E2=80=94=20build=5Fgeometries,=20[geometry]=20replicate,=20?= =?UTF-8?q?multi-frame=20file/conformer=20sources,=20every=20seed=20sample?= =?UTF-8?q?d?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The geometry stage now emits N seed structures and the sampling stage samples all of them (per-seed job dirs, pooled candidates, parent hash in provenance) instead of silently dropping everything but frame 0. Producers: replicate=N with derived per-replica seeds, smiles n_conformers>1, file index=":". build_geometry stays as the strict exactly-one convenience. Prerequisite for diffusion-model sources. Co-Authored-By: Claude Fable 5 Claude-Session: https://claude.ai/code/session_01V6f4Z4uLdysBeehYfbQ56k --- ROADMAP.md | 11 ++++ docs/concepts/architecture.md | 2 +- docs/reference/api.md | 5 +- docs/reference/config.md | 19 +++++- skills/traincraft/SKILL.md | 4 ++ src/traincraft/__init__.py | 3 +- src/traincraft/config/models.py | 9 +++ src/traincraft/geometry/__init__.py | 78 +++++++++++++++++++---- src/traincraft/geometry/sources/file.py | 29 +++++++-- src/traincraft/geometry/sources/smiles.py | 70 +++++++++++--------- src/traincraft/orchestration/stages.py | 29 +++++---- tests/test_geometry.py | 65 ++++++++++++++++++- tests/test_smiles_source.py | 11 ++++ tests/test_stages.py | 33 +++++++++- 14 files changed, 301 insertions(+), 67 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index b415bc2..4345820 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -100,6 +100,17 @@ Acceptance (met) - `examples/15_h_graphite_intercalation.toml` and `16_slab_constraints_md.toml` run end-to-end (zero deps); `17_water_box_liquid.toml` runs in the science env. +### ✅ Multi-structure geometry *(done)* + +- The geometry stage emits **N seed structures**, not one: `build_geometries` + is the pipeline API (sources/builders may return a list), the sampling stage + samples *every* seed (per-seed job dirs, pooled candidates, parent hash in + each frame's provenance). Enabled producers: `[geometry] replicate = N` + (derived per-replica seeds → independent packings/alloys), `smiles` + `n_conformers > 1`, `file` `index = ":"` (multi-frame file — the entry point + for externally generated sets). This is the prerequisite for diffusion-model + sources (MatterGen etc.), which will land as multi-yield `source` plugins. + ### Remaining Phase-1 item - Builder: `polymer` (PySoftK). Deferred — the PySoftK dependency is not reliably diff --git a/docs/concepts/architecture.md b/docs/concepts/architecture.md index de825cf..ec2c144 100644 --- a/docs/concepts/architecture.md +++ b/docs/concepts/architecture.md @@ -39,7 +39,7 @@ or draws from it. Every stage takes typed config objects and returns typed outputs: ```python -build_geometry(GeometryConfig) → Structure +build_geometries(GeometryConfig) → list[Structure] make_calculator(CalculatorConfig) → ASE Calculator run_sampling(structure, calc, job, SamplingConfig) → list[Structure] run_funnel(frames, SelectionConfig) → list[Structure] diff --git a/docs/reference/api.md b/docs/reference/api.md index 8e05e48..87c2f98 100644 --- a/docs/reference/api.md +++ b/docs/reference/api.md @@ -15,7 +15,8 @@ cfg = tc.load_config("my_run.toml") # → TrainCraftConfig cfg2 = tc.loads_config(toml_string) # → TrainCraftConfig # Pipeline stages (pure functions — same ones the CLI calls) -structure = tc.build_geometry(cfg.geometry) +seeds = tc.build_geometries(cfg.geometry) # N seed structures +structure = tc.build_geometry(cfg.geometry) # exactly-one convenience calc = tc.make_calculator(cfg.calculator) frames = tc.run_sampling(structure, calc, job, cfg.sampling) selected = tc.run_funnel(frames, cfg.selection) @@ -77,6 +78,8 @@ frames = tc.read_frames("dataset.extxyz") ## Geometry +::: traincraft.geometry.build_geometries + ::: traincraft.geometry.build_geometry --- diff --git a/docs/reference/config.md b/docs/reference/config.md index 5e88f81..c0ac028 100644 --- a/docs/reference/config.md +++ b/docs/reference/config.md @@ -44,11 +44,12 @@ seed = 42 ## `[geometry]` -Specifies the initial structure. Exactly one of `source` or `builder` must be set. -Transforms are optional and applied in order. +Specifies the initial structure(s). Exactly one of `source` or `builder` must be +set. Transforms are optional and applied in order. ```toml [geometry] # section header (optional if using sub-tables) +replicate = 1 # build N independent variants (see below) [geometry.source] # OR [geometry.builder] type = "..." @@ -57,6 +58,17 @@ type = "..." type = "..." ``` +| Field | Type | Default | Description | +|---|---|---|---| +| `replicate` | `int` | `1` | Build the geometry N times. A source/builder with a `seed` field gets a distinct derived seed per replica (base seed + replica index), so stochastic builders yield N *independent* seed structures — e.g. 20 different liquid packings or alloy arrangements. | + +**Multi-structure geometries.** A geometry may resolve to *several* seed +structures — via `replicate`, a `smiles` source with `n_conformers > 1`, or a +`file` source with `index = ":"`. All of them land in +`structures/initial.extxyz`, and **every seed is sampled** by the sampling +stage (candidates are pooled before selection, and each candidate records its +parent seed in its provenance). + --- ## Sources @@ -66,6 +78,7 @@ type = "..." | Field | Type | Default | Description | |---|---|---|---| | `path` | `str` | required | Path to any ASE-readable file (extxyz, POSCAR, CIF, xyz, …) | +| `index` | `int \| str` | `-1` | ASE image index into a multi-frame file: an int picks one frame (`-1` = last), a slice string like `":"` makes **every** frame a seed structure — how a trajectory or an externally generated set enters the pipeline | ### `type = "scratch"` @@ -83,7 +96,7 @@ Requires RDKit (`pixi install -e science`). | Field | Type | Default | Description | |---|---|---|---| | `smiles` | `str` | required | SMILES string (canonicalised automatically) | -| `n_conformers` | `int` | `1` | Number of ETKDG conformers to generate | +| `n_conformers` | `int` | `1` | Number of ETKDG conformers to generate; `> 1` yields one seed structure per conformer | | `optimize` | `bool` | `true` | Run MMFF geometry optimisation | | `seed` | `int \| null` | `null` | RNG seed for conformer embedding | | `vacuum` | `float` | `6.0` | Vacuum padding in Å | diff --git a/skills/traincraft/SKILL.md b/skills/traincraft/SKILL.md index 278ab52..53757a7 100644 --- a/skills/traincraft/SKILL.md +++ b/skills/traincraft/SKILL.md @@ -122,6 +122,10 @@ Map the user's words to config keys (run `traincraft plugins` for the live list) spacing dial. - **Fragments:** framework atoms (tube / slab / substrate) are tagged `tc_fragment = -1`; each mobile molecule gets its own id `>= 0`. +- **Multiple seed structures:** `[geometry] replicate = N` builds N independent + variants (stochastic builders get derived seeds); `smiles` with + `n_conformers > 1` and `file` with `index = ":"` also yield several seeds. + Every seed is sampled and the candidates pooled before selection. ## 📂 Outputs (under `runs//`) diff --git a/src/traincraft/__init__.py b/src/traincraft/__init__.py index aba41e4..fe9c113 100644 --- a/src/traincraft/__init__.py +++ b/src/traincraft/__init__.py @@ -20,7 +20,7 @@ register, ) from .datasets import Dataset, read_frames, write_frames -from .geometry import build_geometry +from .geometry import build_geometries, build_geometry from .labeling import label_frames from .orchestration import run_pipeline from .sampling import run_sampling @@ -41,6 +41,7 @@ "ValidationResult", "Workspace", "available", + "build_geometries", "build_geometry", "get", "label_frames", diff --git a/src/traincraft/config/models.py b/src/traincraft/config/models.py index d035460..68f7917 100644 --- a/src/traincraft/config/models.py +++ b/src/traincraft/config/models.py @@ -43,6 +43,9 @@ class RunConfig(TCModel): class FileSource(TCModel): type: Literal["file"] = "file" path: FsPath # any ASE-readable format + # ASE image index into a multi-frame file: an int (-1 = last frame, the ASE + # default) or a slice string — ":" turns every frame into a seed structure. + index: int | str = -1 class ScratchSource(TCModel): @@ -543,11 +546,17 @@ class GeometryConfig(TCModel): source: SourceConfig | None = None builder: BuilderConfig | None = None transforms: list[TransformConfig] = Field(default_factory=list) + # Build the geometry this many times; a source/builder with a 'seed' field + # gets a distinct derived seed per replica, so stochastic builders yield N + # independent seed structures (packings, alloy arrangements, ...). + replicate: int = 1 @model_validator(mode="after") def _need_one(self) -> GeometryConfig: if self.source is None and self.builder is None: raise ValueError("geometry needs a 'source' or a 'builder'") + if self.replicate < 1: + raise ValueError("geometry 'replicate' must be >= 1") return self diff --git a/src/traincraft/geometry/__init__.py b/src/traincraft/geometry/__init__.py index f24f332..0656a1d 100644 --- a/src/traincraft/geometry/__init__.py +++ b/src/traincraft/geometry/__init__.py @@ -2,6 +2,13 @@ A geometry workflow is a declared ``source|builder`` followed by ordered ``transforms``. Plugins self-register on import below. + +A source or builder may yield one structure or many — SMILES conformers, +multi-frame files, generative models. :func:`build_geometries` is the pipeline +entry point and always returns a list; every downstream stage treats its +elements as independent seed structures. ``replicate = N`` on the geometry +config builds the whole thing N times, deriving a distinct seed per replica +for stochastic plugins (independent packings, alloy arrangements, ...). """ from __future__ import annotations @@ -10,11 +17,11 @@ from . import builders, sources, transforms # noqa: F401 (register plugins) -def build_source(cfg) -> Structure: +def build_source(cfg) -> Structure | list[Structure]: return get("source", cfg.type)(cfg) -def build_builder(cfg) -> Structure: +def build_builder(cfg) -> Structure | list[Structure]: return get("builder", cfg.type)(cfg) @@ -22,15 +29,64 @@ def apply_transform(structure: Structure, cfg) -> Structure: return get("transform", cfg.type)(structure, cfg) +def _reseeded(model, offset: int): + """Copy of a source/builder config with a replica-derived seed. + + Models without a ``seed`` field pass through unchanged (their replicas can + still differ through stochastic transforms such as ``perturb``). + """ + if "seed" not in type(model).model_fields: + return model + base = model.seed if model.seed is not None else 0 + return model.model_copy(update={"seed": base + offset}) + + +def _build_once(geom_cfg, replica: int | None) -> list[Structure]: + cfg = geom_cfg.builder if geom_cfg.builder is not None else geom_cfg.source + if replica is not None: + cfg = _reseeded(cfg, replica) + kind = "builder" if geom_cfg.builder is not None else "source" + built = get(kind, cfg.type)(cfg) + structures = built if isinstance(built, list) else [built] + out: list[Structure] = [] + for s in structures: + for transform_cfg in geom_cfg.transforms: + s = apply_transform(s, transform_cfg) + if replica is not None: + s.provenance.extra["replica"] = replica + out.append(s) + return out + + +def build_geometries(geom_cfg) -> list[Structure]: + """Resolve a :class:`GeometryConfig` into its list of seed structures.""" + if geom_cfg.replicate == 1: + return _build_once(geom_cfg, None) + structures: list[Structure] = [] + for i in range(geom_cfg.replicate): + structures.extend(_build_once(geom_cfg, i)) + return structures + + def build_geometry(geom_cfg) -> Structure: - """Resolve a :class:`GeometryConfig` into a single :class:`Structure`.""" - if geom_cfg.builder is not None: - structure = build_builder(geom_cfg.builder) - else: - structure = build_source(geom_cfg.source) - for transform_cfg in geom_cfg.transforms: - structure = apply_transform(structure, transform_cfg) - return structure + """Resolve a config declaring exactly **one** structure (raise otherwise). + + Convenience for callers that need a single seed; the pipeline itself uses + :func:`build_geometries` so nothing is silently dropped. + """ + structures = build_geometries(geom_cfg) + if len(structures) != 1: + raise ValueError( + f"geometry expands to {len(structures)} structures " + "(replicate/conformers/multi-frame source); use build_geometries()" + ) + return structures[0] -__all__ = ["apply_transform", "build_builder", "build_geometry", "build_source"] +__all__ = [ + "apply_transform", + "build_builder", + "build_geometries", + "build_geometry", + "build_source", +] diff --git a/src/traincraft/geometry/sources/file.py b/src/traincraft/geometry/sources/file.py index e04f638..d5ec362 100644 --- a/src/traincraft/geometry/sources/file.py +++ b/src/traincraft/geometry/sources/file.py @@ -1,4 +1,10 @@ -"""Source: read a structure from any ASE-readable file.""" +"""Source: read structure(s) from any ASE-readable file. + +``index`` selects which image(s) of a multi-frame file to use: an int picks one +(-1, the last, by default), a slice string like ``":"`` yields every frame as +its own seed structure — how a trajectory or an externally generated set (e.g. +diffusion-model output) enters the pipeline. +""" from __future__ import annotations @@ -8,8 +14,19 @@ @register("source", "file") -def source_file(cfg) -> Structure: - atoms = read(cfg.path) - return Structure.from_ase( - atoms, provenance=Provenance(origin="generated", source=f"source:file:{cfg.path}") - ) +def source_file(cfg) -> Structure | list[Structure]: + images = read(cfg.path, index=cfg.index) + if not isinstance(images, list): + images = [images] + structures = [ + Structure.from_ase( + atoms, + provenance=Provenance( + origin="generated", + source=f"source:file:{cfg.path}", + extra={"frame": i} if len(images) > 1 else {}, + ), + ) + for i, atoms in enumerate(images) + ] + return structures if len(structures) > 1 else structures[0] diff --git a/src/traincraft/geometry/sources/smiles.py b/src/traincraft/geometry/sources/smiles.py index e0d2951..9c0fd07 100644 --- a/src/traincraft/geometry/sources/smiles.py +++ b/src/traincraft/geometry/sources/smiles.py @@ -1,4 +1,9 @@ -"""Source: build a molecule from a SMILES string via RDKit ETKDG.""" +"""Source: build a molecule from a SMILES string via RDKit ETKDG. + +``n_conformers > 1`` returns every embedded conformer as its own seed +structure (they all share the fragment SMILES, so MC conformer moves work +on each). +""" from __future__ import annotations @@ -8,7 +13,7 @@ @register("source", "smiles") -def source_smiles(cfg) -> Structure: +def source_smiles(cfg) -> Structure | list[Structure]: try: from rdkit import Chem from rdkit.Chem import AllChem @@ -41,34 +46,41 @@ def source_smiles(cfg) -> Structure: if cfg.optimize: AllChem.MMFFOptimizeMoleculeConfs(mol, numThreads=1) - conf = mol.GetConformer(0) - positions = np.array(conf.GetPositions()) - symbols = [atom.GetSymbol() for atom in mol.GetAtoms()] - from ase import Atoms - atoms = Atoms(symbols=symbols, positions=positions) - atoms.center(vacuum=cfg.vacuum / 2) - - # All atoms form a single mobile fragment (id 0). - set_fragments(atoms, np.zeros(len(atoms), dtype=int)) - + symbols = [atom.GetSymbol() for atom in mol.GetAtoms()] canonical = Chem.MolToSmiles(Chem.MolFromSmiles(cfg.smiles)) - return Structure.from_ase( - atoms, - provenance=Provenance( - origin="generated", - source=f"source:smiles:{cfg.smiles}", - extra={ - "smiles": canonical, - "n_conformers": cfg.n_conformers, - # Record the *original* SMILES (not the canonical one) so a conformer - # rebuild reproduces the exact atom order of `atoms` — the MC - # conformer move copies coordinates index-for-index, so a reordered - # rebuild would put each element's coords on the wrong atom. See - # sampling.monte_carlo._move_conformer. - "fragment_smiles": {"0": cfg.smiles}, - }, - ), - ) + structures: list[Structure] = [] + for k, conf_id in enumerate(ids): + positions = np.array(mol.GetConformer(conf_id).GetPositions()) + atoms = Atoms(symbols=symbols, positions=positions) + atoms.center(vacuum=cfg.vacuum / 2) + + # All atoms form a single mobile fragment (id 0). + set_fragments(atoms, np.zeros(len(atoms), dtype=int)) + + extra = { + "smiles": canonical, + "n_conformers": cfg.n_conformers, + # Record the *original* SMILES (not the canonical one) so a conformer + # rebuild reproduces the exact atom order of `atoms` — the MC + # conformer move copies coordinates index-for-index, so a reordered + # rebuild would put each element's coords on the wrong atom. See + # sampling.monte_carlo._move_conformer. + "fragment_smiles": {"0": cfg.smiles}, + } + if len(ids) > 1: + extra["conformer"] = k + structures.append( + Structure.from_ase( + atoms, + provenance=Provenance( + origin="generated", + source=f"source:smiles:{cfg.smiles}", + extra=extra, + ), + ) + ) + + return structures if len(structures) > 1 else structures[0] diff --git a/src/traincraft/orchestration/stages.py b/src/traincraft/orchestration/stages.py index 007c499..44d7fe5 100644 --- a/src/traincraft/orchestration/stages.py +++ b/src/traincraft/orchestration/stages.py @@ -7,10 +7,10 @@ in order in one process. Artifacts (under the run workspace): - geometry -> structures/initial.extxyz - sample -> candidates/candidates.extxyz + geometry -> structures/initial.extxyz (N seed structures) + sample -> candidates/candidates.extxyz (every seed sampled, pooled) select -> selected/selected.extxyz - label -> labeled_dft/labeled.extxyz (+ manifest.json, frame_*/) + label -> labeled_dft/labeled.extxyz (+ manifest.json, receipts.jsonl) dataset -> / (a Dataset) train -> model/ (mace_run_train: .model + manifest.json) @@ -40,7 +40,7 @@ from ..config import TrainCraftConfig from ..core import Workspace from ..datasets import Dataset, read_frames, write_frames -from ..geometry import build_geometry +from ..geometry import build_geometries from ..labeling import label_frames from ..sampling import run_sampling from ..selection import run_funnel @@ -209,13 +209,13 @@ def stage_geometry(config, ws, force=False): raise ValueError("config has no [geometry] section: nothing to build") _emit(ws, "geometry", "start") t0 = time.perf_counter() - structure = build_geometry(config.geometry) + structures = build_geometries(config.geometry) ws.subdir("structures") - write_frames(out, [structure]) + write_frames(out, structures) _write_key(out, key) - _emit(ws, "geometry", "done", n_frames=1, + _emit(ws, "geometry", "done", n_frames=len(structures), wall_seconds=round(time.perf_counter() - t0, 2), artifact=str(out)) - return [structure] + return structures @_instrumented @@ -230,12 +230,17 @@ def stage_sample(config, ws, force=False): return read_frames(out) if config.calculator is None: raise ValueError("[sampling] needs a [calculator]") - structure = _latest_upstream(ws, "sample")[0] + seeds = _latest_upstream(ws, "sample") calc = make_calculator(config.calculator) - job = ws.job("candidates") - _emit(ws, "sample", "start") + _emit(ws, "sample", "start", n_in=len(seeds)) t0 = time.perf_counter() - candidates = run_sampling(structure, calc, job, config.sampling) + candidates: list = [] + for i, seed in enumerate(seeds): + # Every seed structure is sampled; each gets its own sampler job dir so + # trajectory artifacts don't collide. Seeds number 10s-100s (conformers, + # replicas) — frame-scale fan-out (100k+) must shard per worker instead. + job = ws.job("candidates") if len(seeds) == 1 else ws.job("candidates", f"seed_{i:03d}") + candidates.extend(run_sampling(seed, calc, job, config.sampling)) write_frames(out, candidates) _write_key(out, key) _emit(ws, "sample", "done", n_frames=len(candidates), diff --git a/tests/test_geometry.py b/tests/test_geometry.py index 4b3f895..e6f989d 100644 --- a/tests/test_geometry.py +++ b/tests/test_geometry.py @@ -1,12 +1,19 @@ from __future__ import annotations +import pytest +from ase.build import bulk +from ase.io import write + from traincraft.config.models import ( + AlloyComponent, + CrystalBuilder, + FileSource, GeometryConfig, MoleculeBuilder, NanotubeBuilder, VacuumTransform, ) -from traincraft.geometry import build_geometry +from traincraft.geometry import build_geometries, build_geometry def test_nanotube_builder(): @@ -23,3 +30,59 @@ def test_molecule_builder_with_transform(): s = build_geometry(g) assert len(s.atoms) == 3 assert "vacuum" in s.provenance.transforms + + +def test_build_geometries_single_config_gives_one(): + structures = build_geometries(GeometryConfig(builder=MoleculeBuilder(name="H2O"))) + assert len(structures) == 1 + + +def _alloy(replicate): + return GeometryConfig( + builder=CrystalBuilder( + name="Cu", crystalstructure="fcc", a=3.6, cubic=True, supercell=(2, 2, 2), + composition=[AlloyComponent(element="Ni", ratio=0.5)], seed=7, + ), + replicate=replicate, + ) + + +def test_replicate_builds_independent_structures(): + structures = build_geometries(_alloy(3)) + assert len(structures) == 3 + assert [s.provenance.extra["replica"] for s in structures] == [0, 1, 2] + # derived per-replica seeds -> different alloy arrangements... + assert len({tuple(s.atoms.get_chemical_symbols()) for s in structures}) > 1 + # ...but the same composition + assert len({tuple(sorted(s.atoms.get_chemical_symbols())) for s in structures}) == 1 + + +def test_replicate_is_deterministic(): + first = [s.hash for s in build_geometries(_alloy(3))] + second = [s.hash for s in build_geometries(_alloy(3))] + assert first == second + + +def test_build_geometry_rejects_multi_structure_config(): + with pytest.raises(ValueError, match="expands to 2"): + build_geometry(_alloy(2)) + + +def test_replicate_must_be_positive(): + with pytest.raises(ValueError, match="replicate"): + GeometryConfig(builder=MoleculeBuilder(name="H2O"), replicate=0) + + +def test_file_source_reads_all_frames(tmp_path): + path = tmp_path / "seeds.extxyz" + write(str(path), [bulk("Cu", "fcc", a=3.6 + 0.05 * i) for i in range(3)]) + + structures = build_geometries( + GeometryConfig(source=FileSource(path=str(path), index=":")) + ) + assert len(structures) == 3 + assert [s.provenance.extra["frame"] for s in structures] == [0, 1, 2] + + # default index keeps the old behavior: one structure, the last frame + last = build_geometry(GeometryConfig(source=FileSource(path=str(path)))) + assert last.hash == structures[-1].hash diff --git a/tests/test_smiles_source.py b/tests/test_smiles_source.py index 12f7240..a1ea53e 100644 --- a/tests/test_smiles_source.py +++ b/tests/test_smiles_source.py @@ -59,3 +59,14 @@ def test_deterministic_with_seed(): np.testing.assert_allclose( s1.atoms.get_positions(), s2.atoms.get_positions(), atol=1e-4 ) + + +def test_multiple_conformers_all_returned(): + cfg = SmilesSource(smiles="OCCCO", n_conformers=3, seed=1) + out = source_smiles(cfg) + assert isinstance(out, list) + assert len(out) == 3 + assert len({s.hash for s in out}) == 3 # geometrically distinct + assert [s.provenance.extra["conformer"] for s in out] == [0, 1, 2] + # every conformer keeps the fragment SMILES needed by MC conformer moves + assert all(s.provenance.extra["fragment_smiles"] == {"0": "OCCCO"} for s in out) diff --git a/tests/test_stages.py b/tests/test_stages.py index 7ecff8c..6b443c7 100644 --- a/tests/test_stages.py +++ b/tests/test_stages.py @@ -1,6 +1,7 @@ from __future__ import annotations from traincraft.config.models import ( + AlloyComponent, CrystalBuilder, DatasetConfig, EmtCalc, @@ -74,13 +75,13 @@ def test_unchanged_config_does_not_rebuild(tmp_path, monkeypatch): run_stage("geometry", cfg, ws) calls = {"n": 0} - real = st.build_geometry + real = st.build_geometries def counting(geometry_cfg): calls["n"] += 1 return real(geometry_cfg) - monkeypatch.setattr(st, "build_geometry", counting) + monkeypatch.setattr(st, "build_geometries", counting) run_stage("geometry", cfg, ws) # same config -> cached, no rebuild assert calls["n"] == 0 @@ -96,6 +97,34 @@ def test_changed_geometry_config_invalidates(tmp_path): assert len(big.atoms) != len(small.atoms) +def test_multi_seed_geometry_flows_through_sampling(tmp_path): + cfg = _cfg(tmp_path).model_copy( + update={ + "geometry": GeometryConfig( + builder=CrystalBuilder( + name="Cu", crystalstructure="fcc", a=3.6, cubic=True, + supercell=(2, 2, 2), + composition=[AlloyComponent(element="Ni", ratio=0.5)], + seed=3, + ), + replicate=2, + ) + } + ) + ws = workspace_for(cfg) + + seeds = run_stage("geometry", cfg, ws) + assert len(seeds) == 2 + assert seeds[0].hash != seeds[1].hash # replica-derived seeds -> distinct alloys + + candidates = run_stage("sample", cfg, ws) + # every seed structure was sampled, and each frame knows its parent + parents = {s.provenance.parents[0] for s in candidates} + assert parents == {s.hash for s in seeds} + assert (ws.root / "candidates" / "seed_000" / "md.traj").exists() + assert (ws.root / "candidates" / "seed_001" / "md.traj").exists() + + def test_geometry_change_cascades_to_sample(tmp_path): cfg = _cfg(tmp_path) ws = workspace_for(cfg) From a48e281e019c9d41164e77e66c3331e625c8ccd0 Mon Sep 17 00:00:00 2001 From: David Abbasi Perez Date: Sat, 11 Jul 2026 23:54:17 +0200 Subject: [PATCH 09/15] =?UTF-8?q?feat(state):=20submitted/queued=20job=20e?= =?UTF-8?q?vents=20=E2=80=94=20accumulate-on-start=20fold,=20queued=20in?= =?UTF-8?q?=20the=20status=20ladder,=20shard-aware=20label=20progress?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Fable 5 Claude-Session: https://claude.ai/code/session_017RmprSjfXNtRV84X9cdkwS --- src/traincraft/cli.py | 2 ++ src/traincraft/state.py | 64 +++++++++++++++++++++++++++-------------- tests/test_state.py | 44 ++++++++++++++++++++++++++++ 3 files changed, 88 insertions(+), 22 deletions(-) diff --git a/src/traincraft/cli.py b/src/traincraft/cli.py index 0f3e9e6..479653a 100644 --- a/src/traincraft/cli.py +++ b/src/traincraft/cli.py @@ -52,6 +52,7 @@ _STATUS_STYLE = { "completed": "green", "running": "yellow", + "queued": "magenta", "failed": "bold red", "partial": "cyan", "empty": "dim", @@ -60,6 +61,7 @@ "done": "green", "cached": "dim green", "running": "yellow", + "queued": "magenta", "failed": "bold red", "pending": "dim", } diff --git a/src/traincraft/state.py b/src/traincraft/state.py index 8a453c6..261362f 100644 --- a/src/traincraft/state.py +++ b/src/traincraft/state.py @@ -31,7 +31,13 @@ EVENTS_NAME = "events.jsonl" INDEX_NAME = "index.db" -_STAGE_STATE = {"start": "running", "done": "done", "skipped": "cached", "failed": "failed"} +_STAGE_STATE = { + "submitted": "queued", # handed to a scheduler; job_id in the event data + "start": "running", + "done": "done", + "skipped": "cached", + "failed": "failed", +} def log_event(run_dir: str | Path, stage: str, event: str, **data) -> None: @@ -72,21 +78,28 @@ def _label_progress(run_dir: Path, since_ts: str | None) -> dict | None: """Live per-frame counts for a running label stage, from receipts.jsonl.""" from .labeling import RECEIPTS_NAME # local import: avoid cycle at module load - receipts = run_dir / "labeled_dft" / RECEIPTS_NAME - if not receipts.exists(): - return None - n_ok = n_failed = 0 - for line in receipts.read_text().splitlines(): - try: - rec = json.loads(line) - except json.JSONDecodeError: + label_dir = run_dir / "labeled_dft" + # Serial labeling appends to one receipts file; sharded labeling to one per + # shard dir (bounded by worker count, never per frame). + paths = [label_dir / RECEIPTS_NAME, *sorted(label_dir.glob(f"shard_*/{RECEIPTS_NAME}"))] + n_ok = n_failed = seen = 0 + for path in paths: + if not path.exists(): continue - if since_ts and rec.get("ts", "") < since_ts: - continue # receipts from an earlier attempt - if rec.get("status") == "ok": - n_ok += 1 - elif rec.get("status") == "failed": - n_failed += 1 + seen += 1 + for line in path.read_text().splitlines(): + try: + rec = json.loads(line) + except json.JSONDecodeError: + continue + if since_ts and rec.get("ts", "") < since_ts: + continue # receipts from an earlier attempt + if rec.get("status") == "ok": + n_ok += 1 + elif rec.get("status") == "failed": + n_failed += 1 + if not seen: + return None return {"n_done": n_ok, "n_failed": n_failed} @@ -94,9 +107,10 @@ def run_status(run_dir: str | Path) -> dict: """Fold a run's event log into its current status. Returns ``{"name", "status", "engine", "planned", "stages": {stage: {...}}, - "started", "updated"}`` where ``status`` is one of ``empty | running | - failed | completed | partial`` (partial: some stages done, plan unknown or - unfinished, nothing currently running). + "started", "updated"}`` where ``status`` is one of ``empty | queued | + running | failed | completed | partial`` (queued: submitted to a scheduler, + nothing running yet; partial: some stages done, plan unknown or unfinished, + nothing currently running). """ run_dir = Path(run_dir) events = read_events(run_dir) @@ -115,15 +129,19 @@ def run_status(run_dir: str | Path) -> dict: engine = data.get("engine", engine) planned = data.get("stages", planned) continue - if ev == "start": - stages[name] = {"state": "running", "started": ts, **data} - elif ev in _STAGE_STATE: + if ev in _STAGE_STATE: + # Accumulate, never replace: a "start" must not drop the job_id + # recorded by an earlier "submitted" event. st = stages.setdefault(name, {}) st.update(data) st["state"] = _STAGE_STATE[ev] + if ev == "start": + st["started"] = ts + # Sharded labeling emits no "start" until the merge job, so live progress + # is also relevant while the stage is only queued (shards may be running). label = stages.get("label") - if label is not None and label["state"] == "running": + if label is not None and label["state"] in ("queued", "running"): progress = _label_progress(run_dir, label.get("started")) if progress is not None: label["progress"] = progress @@ -135,6 +153,8 @@ def run_status(run_dir: str | Path) -> dict: status = "failed" elif "running" in states: status = "running" + elif "queued" in states: + status = "queued" elif planned and all( stages.get(p, {}).get("state") in ("done", "cached") for p in planned ): diff --git a/tests/test_state.py b/tests/test_state.py index 145f0f6..efe8287 100644 --- a/tests/test_state.py +++ b/tests/test_state.py @@ -103,6 +103,50 @@ def test_run_status_label_progress_from_receipts(tmp_path): assert st["stages"]["label"]["progress"] == {"n_done": 3, "n_failed": 1} +def test_submitted_event_reads_as_queued(tmp_path): + log_event(tmp_path, "run", "start", engine="slurm", stages=["geometry", "sample"]) + log_event(tmp_path, "geometry", "submitted", job_id="101", host="leonardo") + log_event(tmp_path, "sample", "submitted", job_id="102", host="leonardo") + + st = run_status(tmp_path) + assert st["status"] == "queued" + assert st["stages"]["geometry"]["state"] == "queued" + assert st["stages"]["geometry"]["job_id"] == "101" + + +def test_start_keeps_job_id_from_submitted(tmp_path): + log_event(tmp_path, "run", "start", engine="slurm", stages=["geometry"]) + log_event(tmp_path, "geometry", "submitted", job_id="101") + log_event(tmp_path, "geometry", "start") + + st = run_status(tmp_path) + assert st["status"] == "running" + geo = st["stages"]["geometry"] + assert geo["state"] == "running" + assert geo["job_id"] == "101" # accumulated, not replaced + assert geo["started"] is not None + + log_event(tmp_path, "geometry", "done", n_frames=1) + assert run_status(tmp_path)["status"] == "completed" + + +def test_label_progress_sums_shard_receipts(tmp_path): + log_event(tmp_path, "run", "start", engine="slurm", stages=["label"]) + log_event(tmp_path, "label", "submitted", job_id="7") # sharded: no start yet + for shard, statuses in enumerate([("ok", "ok"), ("ok", "failed")]): + d = tmp_path / "labeled_dft" / f"shard_{shard:02d}" + d.mkdir(parents=True) + lines = [ + {"ts": "2099-01-01T00:00:00+00:00", "i": i, "status": s} + for i, s in enumerate(statuses) + ] + (d / "receipts.jsonl").write_text("\n".join(json.dumps(x) for x in lines) + "\n") + + st = run_status(tmp_path) + assert st["stages"]["label"]["state"] == "queued" + assert st["stages"]["label"]["progress"] == {"n_done": 3, "n_failed": 1} + + def test_pipeline_emits_events_and_completes(tmp_path): cfg = _config(tmp_path) run_pipeline(cfg) From 0f208f6c5cd87deaf650d73614a06cad299d61a3 Mon Sep 17 00:00:00 2001 From: David Abbasi Perez Date: Sat, 11 Jul 2026 23:56:25 +0200 Subject: [PATCH 10/15] =?UTF-8?q?feat(orchestration):=20Transport=20seam?= =?UTF-8?q?=20=E2=80=94=20run/shell/push/pull=20locally=20or=20over=20an?= =?UTF-8?q?=20SSH=20alias,=20with=20a=20fake=20ssh/scp/sbatch/sacct=20test?= =?UTF-8?q?=20harness?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Fable 5 Claude-Session: https://claude.ai/code/session_017RmprSjfXNtRV84X9cdkwS --- src/traincraft/orchestration/transport.py | 76 +++++++++++++++++++++++ tests/conftest.py | 72 +++++++++++++++++++++ tests/test_transport.py | 73 ++++++++++++++++++++++ 3 files changed, 221 insertions(+) create mode 100644 src/traincraft/orchestration/transport.py create mode 100644 tests/conftest.py create mode 100644 tests/test_transport.py diff --git a/src/traincraft/orchestration/transport.py b/src/traincraft/orchestration/transport.py new file mode 100644 index 0000000..cd43e47 --- /dev/null +++ b/src/traincraft/orchestration/transport.py @@ -0,0 +1,76 @@ +"""Local-or-SSH command transport for the Slurm executor. + +One tiny seam decides *where* scheduler commands and file copies run: on this +machine (login-node deployment, ``host=None``) or on a cluster's login node +reached through an SSH alias from ``~/.ssh/config``. Everything above it — +rendering, submission, polling — is transport-agnostic, which is also the +seam a future multi-cluster router will use (one Transport per cluster). + +SSH calls are strictly non-interactive (``BatchMode=yes``): a missing key or +expired credential fails fast instead of hanging on a prompt. Connection +multiplexing (ControlMaster/ControlPersist) is the alias's business in +``~/.ssh/config``, not ours. +""" + +from __future__ import annotations + +import shlex +import shutil +import subprocess +from dataclasses import dataclass +from pathlib import Path + +_SSH_OPTS = ["-o", "BatchMode=yes", "-o", "ConnectTimeout=10"] + + +@dataclass(frozen=True) +class Transport: + """Run commands and copy files either locally or on ``host`` over SSH.""" + + host: str | None = None # SSH alias; None = run everything locally + + def run(self, args: list[str], *, check: bool = True) -> subprocess.CompletedProcess: + """Run an argv (no shell). Remote: ``ssh -- ``.""" + if self.host is None: + cmd = args + else: + cmd = ["ssh", *_SSH_OPTS, self.host, "--", shlex.join(args)] + return subprocess.run(cmd, capture_output=True, text=True, check=check) + + def shell(self, script: str, *, check: bool = True) -> subprocess.CompletedProcess: + """Run a shell snippet through a login shell ($VAR expansion, globs).""" + if self.host is None: + cmd = ["bash", "-lc", script] + else: + cmd = ["ssh", *_SSH_OPTS, self.host, "--", f"bash -lc {shlex.quote(script)}"] + return subprocess.run(cmd, capture_output=True, text=True, check=check) + + def push(self, local: Path | str, remote: str) -> None: + """Copy a local file to ``remote`` (a path on the transport's side).""" + if self.host is None: + if str(local) != remote: + shutil.copyfile(local, remote) + return + subprocess.run( + ["scp", "-q", *_SSH_OPTS, str(local), f"{self.host}:{remote}"], + capture_output=True, text=True, check=True, + ) + + def pull(self, remote: str, local: Path | str) -> bool: + """Copy ``remote`` back to a local path; False if the file is missing.""" + if self.host is None: + if not Path(remote).is_file(): + return False + if str(local) != remote: + shutil.copyfile(remote, local) + return True + res = subprocess.run( + ["scp", "-q", *_SSH_OPTS, f"{self.host}:{remote}", str(local)], + capture_output=True, text=True, check=False, + ) + return res.returncode == 0 + + +def transport_for(slurm_cfg) -> Transport: + """The transport a ``[orchestration.slurm]`` config asks for.""" + return Transport(host=getattr(slurm_cfg, "host", None)) diff --git a/tests/conftest.py b/tests/conftest.py new file mode 100644 index 0000000..9416257 --- /dev/null +++ b/tests/conftest.py @@ -0,0 +1,72 @@ +"""Shared fixtures: a fake `ssh`/`scp`/`sbatch`/`sacct` toolchain on PATH. + +The shims turn the whole remote-submission flow into a local one — `ssh host +-- cmd` executes `cmd` in a local shell (where `sbatch` resolves to the shim +again), `scp` becomes `cp` — so the executor's real code paths run end-to-end +against a tmp-path "cluster" with no scheduler or network anywhere. +""" + +from __future__ import annotations + +import os + +import pytest + +_SSH = """#!/usr/bin/env bash +# fake ssh: drop options and the host, run the command string locally +while [[ $# -gt 0 ]]; do + case "$1" in + -o) shift 2 ;; + --) shift; break ;; + -*) shift ;; + *) shift ;; # the host alias + esac +done +exec bash -c "$*" +""" + +_SCP = """#!/usr/bin/env bash +# fake scp: strip options and `host:` prefixes, then plain cp +args=() +while [[ $# -gt 0 ]]; do + case "$1" in + -o) shift 2 ;; + -*) shift ;; + *) args+=("$1"); shift ;; + esac +done +exec cp "${args[0]#*:}" "${args[1]#*:}" +""" + +_SBATCH = """#!/usr/bin/env bash +# fake sbatch: log argv, hand out sequential job ids +dir="$(cd "$(dirname "$0")" && pwd)" +printf '%s\\n' "$*" >> "$dir/sbatch.log" +n=$(( $(cat "$dir/sbatch.count" 2>/dev/null || echo 0) + 1 )) +echo "$n" > "$dir/sbatch.count" +echo "Submitted batch job $((1000 + n))" +""" + +_SACCT = """#!/usr/bin/env bash +# fake sacct: log argv, replay whatever the test staged in sacct.out +dir="$(cd "$(dirname "$0")" && pwd)" +printf '%s\\n' "$*" >> "$dir/sacct.log" +cat "$dir/sacct.out" 2>/dev/null +exit 0 +""" + + +@pytest.fixture +def fake_bin(tmp_path_factory, monkeypatch): + """A dir of ssh/scp/sbatch/sacct shims, prepended to PATH. + + Returns the dir; tests read `sbatch.log`/`sacct.log` for the recorded + argv and write `sacct.out` to stage poll responses. + """ + bin_dir = tmp_path_factory.mktemp("fake_bin") + for name, body in [("ssh", _SSH), ("scp", _SCP), ("sbatch", _SBATCH), ("sacct", _SACCT)]: + shim = bin_dir / name + shim.write_text(body) + shim.chmod(0o755) + monkeypatch.setenv("PATH", f"{bin_dir}{os.pathsep}{os.environ['PATH']}") + return bin_dir diff --git a/tests/test_transport.py b/tests/test_transport.py new file mode 100644 index 0000000..3c74bcb --- /dev/null +++ b/tests/test_transport.py @@ -0,0 +1,73 @@ +"""Transport: the local-or-SSH seam under the Slurm executor.""" + +from __future__ import annotations + +import subprocess + +import pytest + +from traincraft.orchestration.transport import Transport, transport_for + + +def test_local_run_is_plain_subprocess(): + res = Transport().run(["echo", "hello world"]) + assert res.stdout.strip() == "hello world" + + +def test_local_shell_expands(): + res = Transport().shell("echo $((2 + 2))") + assert res.stdout.strip() == "4" + + +def test_local_push_pull_roundtrip(tmp_path): + src = tmp_path / "a.txt" + src.write_text("payload") + dst = tmp_path / "b.txt" + Transport().push(src, str(dst)) + assert dst.read_text() == "payload" + back = tmp_path / "c.txt" + assert Transport().pull(str(dst), back) is True + assert back.read_text() == "payload" + assert Transport().pull(str(tmp_path / "missing"), back) is False + + +def test_remote_run_quotes_argv(fake_bin): + t = Transport(host="cluster") + res = t.run(["echo", "two words", "$HOME"]) + # shlex.join must keep "two words" one arg and $HOME literal remotely + assert res.stdout.strip() == "two words $HOME" + + +def test_remote_shell_expands_on_the_remote_side(fake_bin, tmp_path): + t = Transport(host="cluster") + res = t.shell(f"V={tmp_path}; echo $V/run") + assert res.stdout.strip() == f"{tmp_path}/run" + + +def test_remote_run_check_raises(fake_bin): + t = Transport(host="cluster") + with pytest.raises(subprocess.CalledProcessError): + t.run(["false"]) + assert t.run(["false"], check=False).returncode != 0 + + +def test_remote_push_pull(fake_bin, tmp_path): + t = Transport(host="cluster") + src = tmp_path / "in.txt" + src.write_text("data") + remote = tmp_path / "remote" / "in.txt" + remote.parent.mkdir() + t.push(src, str(remote)) + assert remote.read_text() == "data" + back = tmp_path / "back.txt" + assert t.pull(str(remote), back) is True + assert back.read_text() == "data" + assert t.pull(str(tmp_path / "remote" / "nope"), back) is False + + +def test_transport_for_reads_host(): + class Cfg: + host = "leo" + + assert transport_for(Cfg()).host == "leo" + assert transport_for(object()).host is None From 252c33e4bc69ecb12df79cd6cbf30f2dc9f5b28b Mon Sep 17 00:00:00 2001 From: David Abbasi Perez Date: Sun, 12 Jul 2026 00:01:53 +0200 Subject: [PATCH 11/15] =?UTF-8?q?feat(slurm):=20SSH=20remote=20submission?= =?UTF-8?q?=20=E2=80=94=20host/remote=5Froot=20on=20profiles,=20resolved?= =?UTF-8?q?=20config=20snapshot=20+=20inputs=20shipped=20to=20the=20cluste?= =?UTF-8?q?r,=20per-stage=20submitted=20events,=20kill-on-invalid-dep?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The local run dir becomes a mirror (scripts, submission events); the remote run dir at remote_root/ is the truth the jobs write. dumps_config round-trips the snapshot (exclude_none only: discriminator type fields are Literal defaults and must survive). Co-Authored-By: Claude Fable 5 Claude-Session: https://claude.ai/code/session_017RmprSjfXNtRV84X9cdkwS --- src/traincraft/config/loader.py | 12 ++ src/traincraft/config/models.py | 13 ++ src/traincraft/orchestration/slurm.py | 209 +++++++++++++++++++++++--- tests/test_cluster_profiles.py | 14 ++ tests/test_remote_submit.py | 124 +++++++++++++++ 5 files changed, 349 insertions(+), 23 deletions(-) create mode 100644 tests/test_remote_submit.py diff --git a/src/traincraft/config/loader.py b/src/traincraft/config/loader.py index 8f1ff26..63ffbe4 100644 --- a/src/traincraft/config/loader.py +++ b/src/traincraft/config/loader.py @@ -40,6 +40,18 @@ def loads_config(text: str) -> TrainCraftConfig: return TrainCraftConfig.model_validate(plain) +def dumps_config(cfg: TrainCraftConfig) -> str: + """Serialize a validated config back to TOML text. + + ``exclude_none`` is load-bearing: TOML has no null, and the models treat + "key absent" and "key = None" identically. Defaults are NOT excluded — + the discriminated unions' ``type`` fields are Literal defaults and must + survive the round-trip. + """ + plain = cfg.model_dump(mode="json", exclude_none=True) + return tomlkit.dumps(plain) + + def _clusters_dir() -> Path: raw = os.environ.get("TRAINCRAFT_CLUSTERS_DIR", _DEFAULT_CLUSTERS_DIR) return Path(os.path.expandvars(os.path.expanduser(raw))) diff --git a/src/traincraft/config/models.py b/src/traincraft/config/models.py index 68f7917..c5fd2d5 100644 --- a/src/traincraft/config/models.py +++ b/src/traincraft/config/models.py @@ -913,6 +913,13 @@ class SlurmConfig(TCModel): # it, so a workflow moves between clusters by changing this one line. Resolved # by the loader before validation; recorded here for provenance. profile: str | None = None + # SSH alias of the cluster's login node (from ``~/.ssh/config``). When set, + # sbatch/sacct run over ssh and the run dir lives at ``remote_root/`` + # on the cluster; the local run dir becomes a mirror (scripts, pulled events). + host: str | None = None + # Base dir for run dirs on the cluster. Deliberately a plain str, not FsPath: + # "$SCRATCH"/"~" must expand on the REMOTE shell at submit, never locally. + remote_root: str | None = None account: str | None = None sif_dir: FsPath = "." # directory holding the .sif images modules: list[str] = Field(default_factory=list) # `module load` names @@ -936,6 +943,12 @@ class SlurmConfig(TCModel): env: dict[str, str] = Field(default_factory=dict) # global exports stages: dict[str, SlurmStage] = Field(default_factory=dict) + @model_validator(mode="after") + def _remote_needs_root(self) -> SlurmConfig: + if self.host and not self.remote_root: + raise ValueError("[orchestration.slurm] 'host' requires 'remote_root'") + return self + class OrchestrationConfig(TCModel): engine: Literal["local", "slurm"] = "local" diff --git a/src/traincraft/orchestration/slurm.py b/src/traincraft/orchestration/slurm.py index aec70ca..e2430b6 100644 --- a/src/traincraft/orchestration/slurm.py +++ b/src/traincraft/orchestration/slurm.py @@ -34,8 +34,8 @@ import logging import re +import shlex import shutil -import subprocess from dataclasses import dataclass, field from pathlib import Path @@ -43,6 +43,7 @@ from ..core import Workspace from ..state import log_event from .stages import enabled_stages, workspace_for +from .transport import Transport, transport_for logger = logging.getLogger(__name__) @@ -98,12 +99,12 @@ def _stage_exec(stage, image, runtime, gpus, slurm, config_path) -> str: return f"apptainer exec{nv}{_bind_flags(slurm.binds)} {slurm.sif_dir}/{image} {inner}" -def _sbatch_header(stage, st, slurm, run_name, ws: Workspace) -> list[str]: +def _sbatch_header(stage, st, slurm, run_name, run_root: str) -> list[str]: lines = [ "#!/bin/bash", f"#SBATCH --job-name={run_name}-{stage}", - f"#SBATCH --output={ws.root}/slurm/{stage}-%j.out", - f"#SBATCH --error={ws.root}/slurm/{stage}-%j.err", + f"#SBATCH --output={run_root}/slurm/{stage}-%j.out", + f"#SBATCH --error={run_root}/slurm/{stage}-%j.err", f"#SBATCH --nodes={st.nodes}", f"#SBATCH --time={st.time}", ] @@ -126,9 +127,22 @@ def _sbatch_header(stage, st, slurm, run_name, ws: Workspace) -> list[str]: return lines -def render_sbatch(stage: str, config: TrainCraftConfig, ws: Workspace, config_path: str) -> str: +def render_sbatch( + stage: str, + config: TrainCraftConfig, + ws: Workspace, + config_path: str, + *, + run_root: str | None = None, +) -> str: + """Render one stage's sbatch script. + + ``run_root`` is the run directory *as seen by the job* — the remote run + dir in SSH mode. Defaults to the local workspace root. + """ from ..config.models import SlurmStage + run_root = run_root or str(ws.root) slurm = config.orchestration.slurm st = slurm.stages.get(stage, SlurmStage()) image = st.image or _DEFAULT_IMAGE[stage] @@ -159,24 +173,31 @@ def render_sbatch(stage: str, config: TrainCraftConfig, ws: Workspace, config_pa exec_line = _stage_exec(stage, image, runtime, gpus, slurm, config_path) body += ["", exec_line, ""] - header = _sbatch_header(stage, st, slurm, config.run.name, ws) + header = _sbatch_header(stage, st, slurm, config.run.name, run_root) return "\n".join(header + body) + "\n" def render( - config: TrainCraftConfig, config_path: str, ws: Workspace | None = None + config: TrainCraftConfig, + config_path: str, + ws: Workspace | None = None, + *, + run_root: str | None = None, ) -> list[StageJob]: - """Write one sbatch script per enabled stage; return the dependency-chained plan.""" + """Write one sbatch script per enabled stage; return the dependency-chained plan. + + Scripts always land in the local ``slurm/`` dir; ``run_root``/``config_path`` + are the paths *the jobs* use, which differ from local ones in SSH mode. + """ if config.orchestration is None or config.orchestration.slurm is None: raise ValueError("slurm executor needs an [orchestration.slurm] section") ws = ws or workspace_for(config) slurm_dir = ws.subdir("slurm") - cfg_abs = str(Path(config_path).resolve()) jobs: list[StageJob] = [] prev: str | None = None for stage in enabled_stages(config): - text = render_sbatch(stage, config, ws, cfg_abs) + text = render_sbatch(stage, config, ws, config_path, run_root=run_root) path = slurm_dir / f"{stage}.sbatch" path.write_text(text) jobs.append(StageJob(stage=stage, script=path, depends_on=prev)) @@ -184,6 +205,38 @@ def render( return jobs +def _parse_job_id(stdout: str) -> str: + match = _JOB_ID_RE.search(stdout) + if not match: + raise RuntimeError(f"could not parse job id from sbatch output: {stdout!r}") + return match.group(1) + + +def _sbatch_chain( + jobs: list[StageJob], + transport: Transport, + ws: Workspace, + slurm, + *, + script_path, +) -> None: + """Submit the rendered jobs afterok-chained, emitting a ``submitted`` event each. + + ``--kill-on-invalid-dep=yes`` keeps a failed upstream from leaving the rest + of the chain PENDING (DependencyNeverSatisfied) forever. + """ + prev_id: str | None = None + for job in jobs: + cmd = ["sbatch", "--kill-on-invalid-dep=yes"] + if prev_id is not None: + cmd.append(f"--dependency=afterok:{prev_id}") + cmd.append(script_path(job)) + out = transport.run(cmd) + job.job_id = prev_id = _parse_job_id(out.stdout) + logger.info("submitted %s as job %s (after %s)", job.stage, job.job_id, job.depends_on) + log_event(ws.root, job.stage, "submitted", job_id=job.job_id, host=slurm.host) + + def submit( config: TrainCraftConfig, config_path: str, @@ -191,10 +244,21 @@ def submit( *, dry_run: bool = False, ) -> list[StageJob]: - """Render scripts and (unless ``dry_run``) submit them with afterok chaining.""" + """Render scripts and (unless ``dry_run``) submit them with afterok chaining. + + With ``[orchestration.slurm] host`` set, everything scheduler-side runs over + SSH: the run dir lives at ``remote_root/`` on the cluster, a + resolved config snapshot and the input files are shipped there, and the + local run dir becomes a mirror (scripts, submission events, pulled state). + """ + if config.orchestration is None or config.orchestration.slurm is None: + raise ValueError("slurm executor needs an [orchestration.slurm] section") ws = ws or workspace_for(config) - jobs = render(config, config_path, ws) + slurm = config.orchestration.slurm + if slurm.host is not None: + return _submit_remote(config, ws, dry_run=dry_run) + jobs = render(config, str(Path(config_path).resolve()), ws) if dry_run or shutil.which("sbatch") is None: if not dry_run: logger.warning( @@ -202,22 +266,121 @@ def submit( ) return jobs - prev_id: str | None = None + _sbatch_chain(jobs, Transport(), ws, slurm, script_path=lambda j: str(j.script)) + log_event( + ws.root, "run", "start", + engine="slurm", + stages=[j.stage for j in jobs], + jobs={j.stage: j.job_id for j in jobs}, + ) + return jobs + + +def _submit_remote( + config: TrainCraftConfig, ws: Workspace, *, dry_run: bool +) -> list[StageJob]: + """SSH-mode submission: ship snapshot + inputs, sbatch on the login node.""" + slurm = config.orchestration.slurm + transport = transport_for(slurm) + + if dry_run: + # No SSH round-trips: render against the unresolved root for inspection. + remote_root = slurm.remote_root.rstrip("/") + else: + # $SCRATCH/~ expand on the REMOTE shell, exactly once, at submit time + # (sbatch does not expand variables in #SBATCH directives). + out = transport.shell(f"echo {slurm.remote_root}") + remote_root = out.stdout.strip().rstrip("/") + if not remote_root: + raise RuntimeError(f"could not resolve remote_root {slurm.remote_root!r}") + + remote_dir = f"{remote_root}/{config.run.name}" + remote_cfg = f"{remote_dir}/config.toml" + jobs = render(config, remote_cfg, ws, run_root=remote_dir) + if dry_run: + return jobs + + transport.shell( + f"mkdir -p {shlex.quote(remote_dir + '/slurm')} {shlex.quote(remote_dir + '/inputs')}" + ) + snapshot = _ship_config(config, transport, remote_dir, remote_root) + mirror_cfg = ws.root / "config.remote.toml" + mirror_cfg.write_text(snapshot) + transport.push(mirror_cfg, remote_cfg) for job in jobs: - cmd = ["sbatch"] - if prev_id is not None: - cmd.append(f"--dependency=afterok:{prev_id}") - cmd.append(str(job.script)) - out = subprocess.run(cmd, capture_output=True, text=True, check=True) - match = _JOB_ID_RE.search(out.stdout) - if not match: - raise RuntimeError(f"could not parse job id from sbatch output: {out.stdout!r}") - job.job_id = prev_id = match.group(1) - logger.info("submitted %s as job %s (after %s)", job.stage, job.job_id, job.depends_on) + transport.push(job.script, f"{remote_dir}/slurm/{job.script.name}") + + _sbatch_chain( + jobs, transport, ws, slurm, + script_path=lambda j: f"{remote_dir}/slurm/{j.script.name}", + ) log_event( ws.root, "run", "start", engine="slurm", stages=[j.stage for j in jobs], jobs={j.stage: j.job_id for j in jobs}, + host=slurm.host, + remote_dir=remote_dir, ) + logger.info("submitted on %s; follow it with: traincraft watch %s", slurm.host, ws.root) return jobs + + +def _ship_config( + config: TrainCraftConfig, transport: Transport, remote_dir: str, remote_root: str +) -> str: + """Build + return the TOML snapshot the remote jobs load; push its input files. + + The snapshot must be self-contained on the cluster: ``run.outdir`` points at + the resolved remote root, ``profile`` is stripped (the profile file does not + exist over there), ``host``/``remote_root`` are stripped (remote jobs are + local to the cluster), and every locally-existing input file is pushed to + ``inputs/`` and referenced by a relative path (the loader resolves it + against the config's own directory). Paths that do not exist locally are + passed through untouched — they are assumed to be cluster-valid. + """ + from ..config.loader import dumps_config + + cfg = config + shipped: dict[str, str] = {} # basename -> original path (duplicate guard) + + def ship(value: str) -> str | None: + p = Path(value) + if not p.is_file(): + return None + if p.name in shipped and shipped[p.name] != str(p): + raise ValueError( + f"input files {shipped[p.name]!r} and {p!r} would collide as " + f"inputs/{p.name} on the cluster; rename one" + ) + shipped[p.name] = str(p) + transport.push(p, f"{remote_dir}/inputs/{p.name}") + return f"inputs/{p.name}" + + if cfg.geometry is not None: + geom_updates: dict = {} + src = cfg.geometry.source + if src is not None and getattr(src, "path", None): + if (rel := ship(src.path)) is not None: + geom_updates["source"] = src.model_copy(update={"path": rel}) + builder = cfg.geometry.builder + if builder is not None and getattr(builder, "file", None): + if (rel := ship(builder.file)) is not None: + geom_updates["builder"] = builder.model_copy(update={"file": rel}) + if geom_updates: + cfg = cfg.model_copy(update={"geometry": cfg.geometry.model_copy(update=geom_updates)}) + + if cfg.validation is not None and cfg.validation.test_file: + if (rel := ship(cfg.validation.test_file)) is not None: + cfg = cfg.model_copy( + update={"validation": cfg.validation.model_copy(update={"test_file": rel})} + ) + + cfg = cfg.model_copy(update={"run": cfg.run.model_copy(update={"outdir": remote_root})}) + slurm_clean = cfg.orchestration.slurm.model_copy( + update={"profile": None, "host": None, "remote_root": None} + ) + cfg = cfg.model_copy( + update={"orchestration": cfg.orchestration.model_copy(update={"slurm": slurm_clean})} + ) + return dumps_config(cfg) diff --git a/tests/test_cluster_profiles.py b/tests/test_cluster_profiles.py index a003a9b..dfec535 100644 --- a/tests/test_cluster_profiles.py +++ b/tests/test_cluster_profiles.py @@ -85,6 +85,20 @@ def test_inline_stage_deep_merges_over_profile_stage(clusters_dir): assert cfg.orchestration.slurm.stages["sample"].gpus == 1 +def test_profile_carries_host_and_remote_root(clusters_dir): + (clusters_dir / "leonardo.toml").write_text( + 'host = "leonardo"\nremote_root = "$SCRATCH/traincraft-runs"\n' + _LEONARDO + ) + cfg = loads_config( + '[orchestration]\nengine = "slurm"\n' + '[orchestration.slurm]\nprofile = "leonardo"\n' + ) + slurm = cfg.orchestration.slurm + assert slurm.host == "leonardo" + # kept verbatim: $SCRATCH must expand on the remote shell, never locally + assert slurm.remote_root == "$SCRATCH/traincraft-runs" + + def test_missing_profile_raises_with_available_listed(clusters_dir): (clusters_dir / "leonardo.toml").write_text(_LEONARDO) with pytest.raises(FileNotFoundError, match="lumi.*leonardo"): diff --git a/tests/test_remote_submit.py b/tests/test_remote_submit.py new file mode 100644 index 0000000..330b65a --- /dev/null +++ b/tests/test_remote_submit.py @@ -0,0 +1,124 @@ +"""SSH-mode submission: snapshot shipping, remote paths, submitted events.""" + +from __future__ import annotations + +import pytest +from ase.build import bulk +from ase.io import write + +from traincraft.config import load_config +from traincraft.config.models import ( + FileSource, + GeometryConfig, + OrchestrationConfig, + RunConfig, + SlurmConfig, + TrainCraftConfig, +) +from traincraft.orchestration import submit_slurm +from traincraft.state import read_events + + +def _remote_cfg(tmp_path, monkeypatch): + """A geometry-only run submitted from a 'VM' to a tmp-path 'cluster'.""" + scratch = tmp_path / "cluster-scratch" + scratch.mkdir() + monkeypatch.setenv("MYSCRATCH", str(scratch)) + seed = tmp_path / "seed.extxyz" + write(seed, bulk("Cu", "fcc", a=3.6)) + mirror = tmp_path / "mirror" + cfg = TrainCraftConfig( + run=RunConfig(name="rrun", outdir=str(mirror)), + geometry=GeometryConfig(source=FileSource(path=str(seed))), + orchestration=OrchestrationConfig( + engine="slurm", + slurm=SlurmConfig(host="cluster", remote_root="$MYSCRATCH/tcruns", account="ACC_1"), + ), + ) + return cfg, scratch, mirror + + +def test_host_requires_remote_root(): + with pytest.raises(ValueError, match="requires 'remote_root'"): + SlurmConfig(host="cluster") + + +def test_remote_submit_ships_and_submits(fake_bin, tmp_path, monkeypatch): + cfg, scratch, mirror = _remote_cfg(tmp_path, monkeypatch) + jobs = submit_slurm(cfg, "ignored.toml") + + remote_dir = scratch / "tcruns" / "rrun" + # remote side: run dir, shipped snapshot, inputs, scripts + assert (remote_dir / "config.toml").is_file() + assert (remote_dir / "inputs" / "seed.extxyz").is_file() + assert (remote_dir / "slurm" / "geometry.sbatch").is_file() + + # the job got a real id from (fake) sbatch, run over ssh + assert jobs[0].job_id == "1001" + sbatch_log = (fake_bin / "sbatch.log").read_text() + assert "--kill-on-invalid-dep=yes" in sbatch_log + assert str(remote_dir / "slurm" / "geometry.sbatch") in sbatch_log + + # scripts reference the REMOTE run dir, resolved (no unexpanded $MYSCRATCH) + script = (remote_dir / "slurm" / "geometry.sbatch").read_text() + assert f"#SBATCH --output={remote_dir}/slurm/geometry-%j.out" in script + assert f"traincraft stage geometry {remote_dir}/config.toml" in script + assert "$MYSCRATCH" not in script + + # mirror side: local copy of scripts + snapshot + submission events + assert (mirror / "rrun" / "slurm" / "geometry.sbatch").is_file() + assert (mirror / "rrun" / "config.remote.toml").is_file() + events = read_events(mirror / "rrun") + sub = [e for e in events if e["event"] == "submitted"] + assert [(e["stage"], e["job_id"], e["host"]) for e in sub] == [("geometry", "1001", "cluster")] + run = [e for e in events if e["stage"] == "run"][0] + assert run["host"] == "cluster" + assert run["remote_dir"] == str(remote_dir) + assert run["jobs"] == {"geometry": "1001"} + + +def test_shipped_snapshot_round_trips_on_the_cluster(fake_bin, tmp_path, monkeypatch): + cfg, scratch, _ = _remote_cfg(tmp_path, monkeypatch) + submit_slurm(cfg, "ignored.toml") + + remote_dir = scratch / "tcruns" / "rrun" + loaded = load_config(remote_dir / "config.toml") + # outdir points at the resolved remote root → same run dir on the cluster + assert loaded.run.outdir == str(scratch / "tcruns") + assert loaded.run.name == "rrun" + # input path rewritten to the shipped copy and resolved against the config dir + assert loaded.geometry.source.path == str(remote_dir / "inputs" / "seed.extxyz") + # no profile/host/remote_root: remote jobs are local to the cluster + assert loaded.orchestration.slurm.profile is None + assert loaded.orchestration.slurm.host is None + assert loaded.orchestration.slurm.remote_root is None + assert loaded.orchestration.slurm.account == "ACC_1" + + +def test_remote_dry_run_renders_without_ssh(fake_bin, tmp_path, monkeypatch): + cfg, scratch, mirror = _remote_cfg(tmp_path, monkeypatch) + jobs = submit_slurm(cfg, "ignored.toml", dry_run=True) + + assert all(j.job_id is None for j in jobs) + assert not (fake_bin / "sbatch.log").exists() # nothing touched the "cluster" + assert not any(scratch.iterdir()) + script = (mirror / "rrun" / "slurm" / "geometry.sbatch").read_text() + assert "$MYSCRATCH/tcruns/rrun" in script # unresolved, for inspection only + + +def test_local_submit_still_uses_local_paths_and_gets_ids(fake_bin, tmp_path, monkeypatch): + cfg, _, mirror = _remote_cfg(tmp_path, monkeypatch) + local = cfg.model_copy( + update={ + "orchestration": OrchestrationConfig( + engine="slurm", slurm=SlurmConfig(account="ACC_1") + ) + } + ) + jobs = submit_slurm(local, "myconfig.toml") + assert jobs[0].job_id == "1001" + script = (mirror / "rrun" / "slurm" / "geometry.sbatch").read_text() + assert f"#SBATCH --output={mirror}/rrun/slurm/geometry-%j.out" in script + events = read_events(mirror / "rrun") + assert [e["event"] for e in events] == ["submitted", "start"] + assert events[0]["host"] is None From 06296b4c8a682b6f9f90587b3285a44acf379637 Mon Sep 17 00:00:00 2001 From: David Abbasi Perez Date: Sun, 12 Jul 2026 00:04:51 +0200 Subject: [PATCH 12/15] =?UTF-8?q?feat(watch):=20traincraft=20watch=20?= =?UTF-8?q?=E2=80=94=20sacct=20polling=20with=20array=20aggregation,=20rem?= =?UTF-8?q?ote=20events/receipts=20ingest=20into=20the=20local=20mirror,?= =?UTF-8?q?=20failed=20events=20for=20queue-killed=20jobs?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Fable 5 Claude-Session: https://claude.ai/code/session_017RmprSjfXNtRV84X9cdkwS --- src/traincraft/cli.py | 43 ++++++ src/traincraft/orchestration/watch.py | 184 ++++++++++++++++++++++++++ tests/test_watch.py | 111 ++++++++++++++++ 3 files changed, 338 insertions(+) create mode 100644 src/traincraft/orchestration/watch.py create mode 100644 tests/test_watch.py diff --git a/src/traincraft/cli.py b/src/traincraft/cli.py index 479653a..5b67c5c 100644 --- a/src/traincraft/cli.py +++ b/src/traincraft/cli.py @@ -231,6 +231,49 @@ def submit( dep = f" after {job.depends_on}" if job.depends_on else "" jid = f" (job {job.job_id})" if job.job_id else "" typer.echo(f" {job.stage}{dep}: {job.script}{jid}") + if not dry_run and cfg.orchestration.slurm.host: + typer.echo(f"follow it with: traincraft watch {config}") + + +_WATCH_EXIT = {"completed": 0, "failed": 1, "in-progress": 3} + + +@app.command(rich_help_panel=_RUN) +def watch( + target: Path = typer.Argument( + ..., exists=True, help="the submitted .toml, or the run directory itself" + ), + interval: float = typer.Option(60.0, "--interval", help="seconds between polls"), + once: bool = typer.Option(False, "--once", help="one pass: refresh state, then exit"), +) -> None: + """Follow a submitted Slurm run until it finishes (Ctrl-C is safe). + + Polls the scheduler (over ssh when the cluster profile has a [cyan]host[/]), + pulls the run's remote events + labeling receipts into the local run dir, + and records queue-level deaths (OOM, timeout, cancel) that the stage + process itself never got to log. Re-entrant: run it again any time. + + Exit code: 0 completed, 1 failed, 3 still in progress (with --once). + + [b]Example[/] + + \b + [cyan]traincraft watch my_run.toml --interval 120[/] + """ + from .orchestration.watch import watch as watch_run + + _setup_logging() + if target.is_dir(): + run_dir = target + else: + cfg = load_config(target) + run_dir = Path(cfg.run.outdir) / cfg.run.name + try: + outcome = watch_run(run_dir, interval=interval, once=once, echo=_console.print) + except ValueError as exc: + typer.echo(str(exc)) + raise typer.Exit(code=1) from exc + raise typer.Exit(code=_WATCH_EXIT.get(outcome, 1)) # --- 3 · inspect --------------------------------------------------------------- diff --git a/src/traincraft/orchestration/watch.py b/src/traincraft/orchestration/watch.py new file mode 100644 index 0000000..92ac2c4 --- /dev/null +++ b/src/traincraft/orchestration/watch.py @@ -0,0 +1,184 @@ +"""Follow a submitted Slurm run: ingest remote state, catch silent job deaths. + +The scheduler advances the DAG (afterok chaining) — this loop only *observes* +and *records*. Each pass: pull the remote ``events.jsonl`` into the local +mirror (exact-line dedup, idempotent), mirror the labeling receipts for live +progress, poll ``sacct`` for every submitted job, and append a ``failed`` +event for any job the queue killed before its stage process could log one +(OOM, TIMEOUT, node failure, a dependency cancel). Because such a job is +dead, there is provably no concurrent writer on the mirror file — the state +layer's single-writer-per-file invariant holds in both SSH and login-node +mode. + +Re-entrant by construction: all state comes from ``events.jsonl``, so any +invocation — including two racing ones — converges on the same picture. The +multi-cluster follow-up slots into the *act* step of the pass (submit the +next stage elsewhere, move data); the loop shape stays the same. +""" + +from __future__ import annotations + +import logging +import time +from pathlib import Path + +from ..state import EVENTS_NAME, log_event, read_events, run_status +from .transport import Transport + +logger = logging.getLogger(__name__) + +# sacct states that mean the job is gone and will not write anything further. +_DEAD = { + "FAILED", "CANCELLED", "TIMEOUT", "OUT_OF_MEMORY", "NODE_FAIL", + "BOOT_FAIL", "DEADLINE", "PREEMPTED", +} +_STAGE_TERMINAL = {"done", "cached", "failed"} + + +def poll_jobs(transport: Transport, job_ids: list[str]) -> dict[str, str]: + """Queue state per submitted job id: ``queued|running|completed|dead:``. + + Uses ``sacct`` (covers finished jobs, unlike squeue). A job array's parent + id aggregates its element rows: dead if any element died and all are + terminal, running if any runs, completed only when every element is. + Ids unknown to sacct (accounting lag) read as ``queued``. + """ + if not job_ids: + return {} + res = transport.run( + ["sacct", "-X", "--parsable2", "--noheader", + "--format=JobID,State,ExitCode", "-j", ",".join(job_ids)], + check=False, + ) + if res.returncode != 0: + raise RuntimeError(f"sacct failed: {res.stderr.strip() or res.stdout.strip()!r}") + + rows: dict[str, list[str]] = {} + for line in res.stdout.splitlines(): + parts = line.split("|") + if len(parts) < 2 or not parts[0]: + continue + parent = parts[0].split("_")[0].split(".")[0] + state = parts[1].split()[0] # "CANCELLED by 1234" -> "CANCELLED" + rows.setdefault(parent, []).append(state) + return {jid: _aggregate(rows.get(jid, [])) for jid in job_ids} + + +def _aggregate(states: list[str]) -> str: + if not states: + return "queued" # not in accounting yet + if any(s == "RUNNING" for s in states): + return "running" + dead = [s for s in states if s in _DEAD] + if all(s in _DEAD or s == "COMPLETED" for s in states): + return f"dead:{dead[0]}" if dead else "completed" + return "queued" + + +def ingest_remote_events(transport: Transport, remote_dir: str, run_dir: Path) -> int: + """Merge the remote ``events.jsonl`` into the local mirror; count new lines. + + Exact-line dedup makes this idempotent, and the remote file is only ever + appended to, so re-pulling is always safe. + """ + tmp = run_dir / (EVENTS_NAME + ".remote") + if not transport.pull(f"{remote_dir}/{EVENTS_NAME}", tmp): + return 0 + local = run_dir / EVENTS_NAME + seen = set(local.read_text().splitlines()) if local.exists() else set() + new = [ + line for line in tmp.read_text().splitlines() + if line.strip() and line not in seen + ] + if new: + with local.open("a") as fh: + fh.write("\n".join(new) + "\n") + tmp.unlink() + return len(new) + + +def pull_label_receipts(transport: Transport, remote_dir: str, run_dir: Path) -> None: + """Mirror the labeling receipts (serial file + shard files) for live progress.""" + res = transport.shell( + f"cat {remote_dir}/labeled_dft/receipts.jsonl " + f"{remote_dir}/labeled_dft/shard_*/receipts.jsonl 2>/dev/null", + check=False, + ) + if res.stdout: + dest = run_dir / "labeled_dft" + dest.mkdir(exist_ok=True) + (dest / "receipts.jsonl").write_text(res.stdout) + + +def _run_meta(run_dir: Path) -> tuple[str | None, str | None, dict[str, str]]: + """host, remote_dir, {stage: job_id} from the latest run start event.""" + host = remote = None + jobs: dict[str, str] = {} + for e in read_events(run_dir): + if e.get("stage") == "run" and e.get("event") == "start" and e.get("jobs"): + host, remote, jobs = e.get("host"), e.get("remote_dir"), e["jobs"] + return host, remote, jobs + + +def watch( + run_dir: str | Path, + *, + interval: float = 60.0, + once: bool = False, + echo=print, +) -> str: + """Poll until every planned stage is terminal; returns the final status. + + Returns ``completed`` / ``failed`` when the run is over, or + ``in-progress`` (only with ``once=True``). + """ + run_dir = Path(run_dir) + host, remote_dir, jobs = _run_meta(run_dir) + if not jobs: + raise ValueError(f"{run_dir} has no submitted Slurm jobs to watch") + transport = Transport(host=host) + last_seen: dict[str, str] = {} + + while True: + if host and remote_dir: + ingest_remote_events(transport, remote_dir, run_dir) + pull_label_receipts(transport, remote_dir, run_dir) + + st = run_status(run_dir) + queue = poll_jobs(transport, list(jobs.values())) + for name, job_id in jobs.items(): + stage = "label" if name == "label_merge" else name + q = queue.get(job_id, "queued") + stage_state = st["stages"].get(stage, {}).get("state") + if q.startswith("dead:") and stage_state not in _STAGE_TERMINAL: + slurm_state = q.split(":", 1)[1] + # The job is dead and its stage never logged a terminal event: + # the queue killed it (OOM/timeout/cancel) — record that here, + # the only writer left. + log_event( + run_dir, stage, "failed", + error=f"slurm: {slurm_state}", slurm_state=slurm_state, job_id=job_id, + ) + st = run_status(run_dir) + + for stage, info in st["stages"].items(): + state = info["state"] + if last_seen.get(stage) != state: + suffix = "" + if state == "failed" and info.get("error"): + suffix = f" ({info['error']})" + progress = info.get("progress") + if progress: + suffix = f" ({progress['n_done']} done / {progress['n_failed']} failed)" + echo(f"{stage:<10} {state}{suffix}") + last_seen[stage] = state + + planned = st["planned"] or list(st["stages"]) + if planned and all( + st["stages"].get(p, {}).get("state") in _STAGE_TERMINAL for p in planned + ): + echo(f"run {st['status']}") + return st["status"] + if once: + return "in-progress" + time.sleep(interval) diff --git a/tests/test_watch.py b/tests/test_watch.py new file mode 100644 index 0000000..8d46126 --- /dev/null +++ b/tests/test_watch.py @@ -0,0 +1,111 @@ +"""The watch loop: sacct polling, silent-death events, remote-state ingest.""" + +from __future__ import annotations + +import json + +import pytest + +from traincraft.orchestration.watch import _aggregate, watch +from traincraft.state import log_event, read_events + + +def _submitted_run(run_dir, *, stages=("geometry",), host=None, remote_dir=None, jobs=None): + jobs = jobs or {s: str(1001 + i) for i, s in enumerate(stages)} + extra = {} + if host: + extra = {"host": host, "remote_dir": remote_dir} + log_event(run_dir, "run", "start", engine="slurm", stages=list(stages), jobs=jobs, **extra) + for s, jid in jobs.items(): + log_event(run_dir, s, "submitted", job_id=jid, host=host) + return jobs + + +def test_aggregate_matrix(): + assert _aggregate([]) == "queued" # accounting lag + assert _aggregate(["PENDING"]) == "queued" + assert _aggregate(["RUNNING", "COMPLETED"]) == "running" + assert _aggregate(["COMPLETED", "COMPLETED"]) == "completed" + assert _aggregate(["COMPLETED", "OUT_OF_MEMORY"]) == "dead:OUT_OF_MEMORY" + assert _aggregate(["CANCELLED"]) == "dead:CANCELLED" + assert _aggregate(["PENDING", "COMPLETED"]) == "queued" + + +def test_silent_death_records_failed_once(fake_bin, tmp_path): + run_dir = tmp_path / "run" + _submitted_run(run_dir) + (fake_bin / "sacct.out").write_text("1001|FAILED|1:0\n") + + assert watch(run_dir, once=True, echo=lambda *_: None) == "failed" + # a second pass must not duplicate the failure + assert watch(run_dir, once=True, echo=lambda *_: None) == "failed" + + failed = [e for e in read_events(run_dir) if e["event"] == "failed"] + assert len(failed) == 1 + assert failed[0]["stage"] == "geometry" + assert failed[0]["slurm_state"] == "FAILED" + assert failed[0]["job_id"] == "1001" + + +def test_pending_run_is_in_progress(fake_bin, tmp_path): + run_dir = tmp_path / "run" + _submitted_run(run_dir) + (fake_bin / "sacct.out").write_text("1001|PENDING|0:0\n") + + assert watch(run_dir, once=True, echo=lambda *_: None) == "in-progress" + assert not [e for e in read_events(run_dir) if e["event"] == "failed"] + + +def test_array_job_aggregates_elements(fake_bin, tmp_path): + run_dir = tmp_path / "run" + _submitted_run(run_dir, stages=("label",), jobs={"label": "2000"}) + (fake_bin / "sacct.out").write_text("2000_0|COMPLETED|0:0\n2000_1|OUT_OF_MEMORY|0:125\n") + + assert watch(run_dir, once=True, echo=lambda *_: None) == "failed" + failed = [e for e in read_events(run_dir) if e["event"] == "failed"] + assert failed[0]["slurm_state"] == "OUT_OF_MEMORY" + + +def test_remote_ingest_dedups_and_completes(fake_bin, tmp_path): + remote = tmp_path / "remote-run" + log_event(remote, "geometry", "start") + log_event(remote, "geometry", "done", n_frames=3) + shard = remote / "labeled_dft" / "shard_00" + shard.mkdir(parents=True) + (shard / "receipts.jsonl").write_text( + json.dumps({"ts": "2099-01-01T00:00:00+00:00", "i": 0, "status": "ok"}) + "\n" + ) + + run_dir = tmp_path / "mirror-run" + _submitted_run(run_dir, host="cluster", remote_dir=str(remote)) + (fake_bin / "sacct.out").write_text("1001|COMPLETED|0:0\n") + + assert watch(run_dir, once=True, echo=lambda *_: None) == "completed" + n_lines = len((run_dir / "events.jsonl").read_text().splitlines()) + # re-watching pulls the same remote events again without duplicating them + assert watch(run_dir, once=True, echo=lambda *_: None) == "completed" + assert len((run_dir / "events.jsonl").read_text().splitlines()) == n_lines + assert (run_dir / "labeled_dft" / "receipts.jsonl").read_text().count('"ok"') == 1 + + states = {e["stage"]: e["event"] for e in read_events(run_dir) if e["stage"] != "run"} + assert states["geometry"] == "done" + + +def test_watch_needs_a_submitted_run(tmp_path): + run_dir = tmp_path / "run" + log_event(run_dir, "geometry", "start") + with pytest.raises(ValueError, match="no submitted Slurm jobs"): + watch(run_dir, once=True) + + +def test_merge_job_failure_lands_on_label_stage(fake_bin, tmp_path): + run_dir = tmp_path / "run" + _submitted_run( + run_dir, stages=("label",), jobs={"label": "3000", "label_merge": "3001"} + ) + (fake_bin / "sacct.out").write_text("3000|COMPLETED|0:0\n3001|TIMEOUT|0:0\n") + + assert watch(run_dir, once=True, echo=lambda *_: None) == "failed" + failed = [e for e in read_events(run_dir) if e["event"] == "failed"] + assert failed[0]["stage"] == "label" + assert failed[0]["slurm_state"] == "TIMEOUT" From 8054d423c53cdbd6fe0577c97c09d68f95144269 Mon Sep 17 00:00:00 2001 From: David Abbasi Perez Date: Sun, 12 Jul 2026 00:11:55 +0200 Subject: [PATCH 13/15] =?UTF-8?q?feat(label):=20sharded=20labeling=20?= =?UTF-8?q?=E2=80=94=20stage=20--shard=20I:N=20/=20--merge-shards,=20Slurm?= =?UTF-8?q?=20job=20array=20+=20merge=20job,=20per-shard=20single-writer?= =?UTF-8?q?=20journal=20dirs?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Shard tasks label frames[i::n] into labeled_dft/shard_XX/ (own work/, receipts, journal — the single-writer invariant holds per dir) and publish nothing; the merge job assembles journals by fingerprint, records misses as failures (never recomputes DFT in its small allocation), and emits the stage's events/artifact/key. shards lives on SlurmStage so changing it never invalidates the label cache key. Co-Authored-By: Claude Fable 5 Claude-Session: https://claude.ai/code/session_017RmprSjfXNtRV84X9cdkwS --- src/traincraft/__init__.py | 3 +- src/traincraft/cli.py | 21 ++++- src/traincraft/config/models.py | 4 + src/traincraft/labeling.py | 80 ++++++++++++++++++ src/traincraft/orchestration/slurm.py | 74 ++++++++++++---- src/traincraft/orchestration/stages.py | 78 ++++++++++++++--- tests/test_shard_label.py | 112 +++++++++++++++++++++++++ tests/test_slurm_executor.py | 60 +++++++++++++ 8 files changed, 398 insertions(+), 34 deletions(-) create mode 100644 tests/test_shard_label.py diff --git a/src/traincraft/__init__.py b/src/traincraft/__init__.py index fe9c113..23984f1 100644 --- a/src/traincraft/__init__.py +++ b/src/traincraft/__init__.py @@ -21,7 +21,7 @@ ) from .datasets import Dataset, read_frames, write_frames from .geometry import build_geometries, build_geometry -from .labeling import label_frames +from .labeling import label_frames, merge_shard_labels from .orchestration import run_pipeline from .sampling import run_sampling from .selection import run_funnel @@ -49,6 +49,7 @@ "loads_config", "make_calculator", "make_rng", + "merge_shard_labels", "read_frames", "register", "run_funnel", diff --git a/src/traincraft/cli.py b/src/traincraft/cli.py index 5b67c5c..1b078bb 100644 --- a/src/traincraft/cli.py +++ b/src/traincraft/cli.py @@ -186,11 +186,20 @@ def stage( name: str = typer.Argument(..., help=f"one of: {', '.join(STAGE_ORDER)}"), config: Path = typer.Argument(..., exists=True, readable=True, help="the .toml to use"), force: bool = typer.Option(False, "--force", help="recompute even if the artifact exists"), + shard: str = typer.Option( + None, "--shard", metavar="I:N", + help="label only: this task labels the I-th of N frame shards", + ), + merge_shards: bool = typer.Option( + False, "--merge-shards", help="label only: assemble shard results into the artifact" + ), ) -> None: """Run one pipeline stage standalone; upstream artifacts come from disk. This is what the Slurm executor dispatches as separate jobs — and how you - train or validate against artifacts you already have. + train or validate against artifacts you already have. Sharded labeling + ([cyan]--shard I:N[/] per task, then one [cyan]--merge-shards[/]) is what + a `shards = N` label stage renders as a job array. [b]Example — train on an existing dataset[/] @@ -198,8 +207,16 @@ def stage( [cyan]pixi run -e mace traincraft stage train my_run.toml[/] """ _setup_logging() + parsed_shard = None + if shard is not None: + try: + i, n = (int(x) for x in shard.split(":")) + parsed_shard = (i, n) + except ValueError: + typer.echo(f"--shard must look like 'I:N' (got {shard!r})") + raise typer.Exit(code=2) from None cfg = load_config(config) - frames = run_stage(name, cfg, force=force) + frames = run_stage(name, cfg, force=force, shard=parsed_shard, merge_shards=merge_shards) typer.echo(f"stage '{name}': {len(frames)} frames") diff --git a/src/traincraft/config/models.py b/src/traincraft/config/models.py index c5fd2d5..73e7b95 100644 --- a/src/traincraft/config/models.py +++ b/src/traincraft/config/models.py @@ -905,6 +905,10 @@ class SlurmStage(TCModel): extra_sbatch: list[str] = Field(default_factory=list) # raw extra "#SBATCH ..." lines pre_commands: list[str] = Field(default_factory=list) # shell lines before the exec env: dict[str, str] = Field(default_factory=dict) # extra exports for this stage + # label stage only: split labeling into a Slurm job array of N shard tasks + # (each with THIS stage's resources) plus a small merge job. Execution-only + # config: changing it never invalidates the label stage's cache key. + shards: int | None = Field(default=None, ge=1) class SlurmConfig(TCModel): diff --git a/src/traincraft/labeling.py b/src/traincraft/labeling.py index d1256c2..7fbac39 100644 --- a/src/traincraft/labeling.py +++ b/src/traincraft/labeling.py @@ -130,6 +130,86 @@ def _compute(atoms, calc, calc_cfg, extra_props: list[str]) -> dict: return props +def merge_shard_labels( + frames: list[Structure], calc_cfg, *, out_dir +) -> tuple[list[Structure], dict]: + """Assemble sharded labeling results for ``frames``; never computes. + + Shard jobs (``label_frames`` into ``shard_XX/`` dirs — one single-writer + dir each) leave per-shard journals; this walks the input frames in order, + takes journal hits by fingerprint, and records misses as failures with the + error recovered from the shard's receipts. A miss is *not* recomputed here + — the merge runs in a small allocation, and the retry path is rerunning + the failed shards (their journals make that incremental). Returns + ``(labeled, manifest)`` and writes ``manifest.json``. + """ + out_dir = Path(out_dir) + extra_props = list(getattr(calc_cfg, "properties", []) or []) + level = _level_of_theory(calc_cfg) + + shard_dirs = sorted(d for d in out_dir.glob("shard_*") if d.is_dir()) + if not shard_dirs: + raise RuntimeError(f"no shard_* dirs under {out_dir}; did the shard jobs run?") + cache: dict[str, Structure] = {} + errors: dict[str, str] = {} + for d in shard_dirs: + cache.update(_journal_cache(d)) + receipts = d / RECEIPTS_NAME + if not receipts.exists(): + continue + for line in receipts.read_text().splitlines(): + try: + rec = json.loads(line) + except json.JSONDecodeError: + continue + if rec.get("status") == "failed": + errors[rec.get("fp")] = rec.get("error", "unknown") + elif rec.get("status") == "ok": # a later retry succeeded + errors.pop(rec.get("fp"), None) + + labeled: list[Structure] = [] + failures: list[dict] = [] + for i, s in enumerate(frames): + fp = _fingerprint(s, level, extra_props) + hit = cache.get(fp) + if hit is not None: + labeled.append(hit.copy()) + else: + failures.append( + { + "frame": i, + "error": errors.get( + fp, "missing from every shard journal (shard job incomplete?)" + ), + } + ) + if frames and not labeled: + raise RuntimeError( + f"no shard produced a single labeled frame out of {len(frames)} " + f"(first error: {failures[0]['error']})" + ) + + manifest = { + "level_of_theory": level, + "calculator": calc_cfg.type, + "properties": ["energy", "forces", "stress", *extra_props], + "n_frames": len(labeled), + "n_attempted": len(frames), + "n_failed": len(failures), + "n_reused": 0, + "n_shards": len(shard_dirs), + "failures": failures, + "origin": "dft_labeled", + "files": { + "receipts": f"shard_*/{RECEIPTS_NAME}", + "journal": f"shard_*/{JOURNAL_NAME}", + "quarantine": f"shard_*/{QUARANTINE_NAME}", + }, + } + (out_dir / "manifest.json").write_text(json.dumps(manifest, indent=2)) + return labeled, manifest + + def label_frames( frames: list[Structure], calc_cfg, *, out_dir=None, on_error: str = "skip" ) -> list[Structure]: diff --git a/src/traincraft/orchestration/slurm.py b/src/traincraft/orchestration/slurm.py index e2430b6..fd87f17 100644 --- a/src/traincraft/orchestration/slurm.py +++ b/src/traincraft/orchestration/slurm.py @@ -90,24 +90,29 @@ def _dft_command(binary: str, image: str, slurm, runtime: str, mpi: str) -> str: return f"{prefix} apptainer exec{_bind_flags(slurm.binds)} {slurm.sif_dir}/{image} {binary}" -def _stage_exec(stage, image, runtime, gpus, slurm, config_path) -> str: +def _stage_exec(stage, image, runtime, gpus, slurm, config_path, extra_args="") -> str: """The line that runs ``traincraft stage`` — wrapped in our image or bare.""" - inner = f"traincraft stage {stage} {config_path}" + inner = f"traincraft stage {stage} {config_path}{extra_args}" if runtime == "native": return inner nv = " --nv" if gpus else "" return f"apptainer exec{nv}{_bind_flags(slurm.binds)} {slurm.sif_dir}/{image} {inner}" -def _sbatch_header(stage, st, slurm, run_name, run_root: str) -> list[str]: +def _sbatch_header( + stage, st, slurm, run_name, run_root: str, array: int | None = None +) -> list[str]: + log = "%A_%a" if array else "%j" # array tasks get per-element logs lines = [ "#!/bin/bash", f"#SBATCH --job-name={run_name}-{stage}", - f"#SBATCH --output={run_root}/slurm/{stage}-%j.out", - f"#SBATCH --error={run_root}/slurm/{stage}-%j.err", + f"#SBATCH --output={run_root}/slurm/{stage}-{log}.out", + f"#SBATCH --error={run_root}/slurm/{stage}-{log}.err", f"#SBATCH --nodes={st.nodes}", f"#SBATCH --time={st.time}", ] + if array: + lines.append(f"#SBATCH --array=0-{array - 1}") if slurm.account: lines.append(f"#SBATCH --account={slurm.account}") if st.partition: @@ -134,19 +139,27 @@ def render_sbatch( config_path: str, *, run_root: str | None = None, + job_key: str | None = None, + array: int | None = None, + extra_args: str = "", ) -> str: """Render one stage's sbatch script. ``run_root`` is the run directory *as seen by the job* — the remote run - dir in SSH mode. Defaults to the local workspace root. + dir in SSH mode; defaults to the local workspace root. ``job_key`` names + the job and selects its ``stages.`` overrides when it differs from + the executed stage (the label merge job runs ``stage label`` under the + key ``label_merge``). ``array`` renders a job array of that many tasks; + ``extra_args`` is appended to the ``traincraft stage`` line. """ from ..config.models import SlurmStage run_root = run_root or str(ws.root) + job_key = job_key or stage slurm = config.orchestration.slurm - st = slurm.stages.get(stage, SlurmStage()) - image = st.image or _DEFAULT_IMAGE[stage] - gpus = st.gpus if st.gpus is not None else _DEFAULT_GPUS.get(stage) + st = slurm.stages.get(job_key, SlurmStage()) + image = st.image or _DEFAULT_IMAGE.get(job_key) or _DEFAULT_IMAGE[stage] + gpus = st.gpus if st.gpus is not None else _DEFAULT_GPUS.get(job_key) runtime = st.runtime or slurm.runtime mpi = st.mpi or slurm.mpi binds = _bind_flags(slurm.binds) @@ -158,7 +171,8 @@ def render_sbatch( body += [f'export {k}="{v}"' for k, v in slurm.env.items()] body += [f'export {k}="{v}"' for k, v in st.env.items()] - if stage == "label": + # The merge job assembles shard journals and never runs a DFT binary. + if stage == "label" and "--merge-shards" not in extra_args: if slurm.aims_command: aims = slurm.aims_command.format(binds=binds, sif_dir=slurm.sif_dir, mpi=mpi) else: @@ -170,10 +184,10 @@ def render_sbatch( body.append(f'export TRAINCRAFT_AIMS_COMMAND="{aims}"') body.append(f'export TRAINCRAFT_PW_COMMAND="{pw}"') - exec_line = _stage_exec(stage, image, runtime, gpus, slurm, config_path) + exec_line = _stage_exec(stage, image, runtime, gpus, slurm, config_path, extra_args) body += ["", exec_line, ""] - header = _sbatch_header(stage, st, slurm, config.run.name, run_root) + header = _sbatch_header(job_key, st, slurm, config.run.name, run_root, array=array) return "\n".join(header + body) + "\n" @@ -192,16 +206,36 @@ def render( if config.orchestration is None or config.orchestration.slurm is None: raise ValueError("slurm executor needs an [orchestration.slurm] section") ws = ws or workspace_for(config) + slurm = config.orchestration.slurm + for name, st in slurm.stages.items(): + if st.shards and st.shards > 1 and name != "label": + raise ValueError(f"'shards' applies to the label stage only, not {name!r}") slurm_dir = ws.subdir("slurm") jobs: list[StageJob] = [] prev: str | None = None - for stage in enabled_stages(config): - text = render_sbatch(stage, config, ws, config_path, run_root=run_root) - path = slurm_dir / f"{stage}.sbatch" + + def add(stage: str, filename: str, **render_kw) -> None: + nonlocal prev + text = render_sbatch(stage, config, ws, config_path, run_root=run_root, **render_kw) + path = slurm_dir / filename path.write_text(text) - jobs.append(StageJob(stage=stage, script=path, depends_on=prev)) - prev = stage + key = render_kw.get("job_key", stage) + jobs.append(StageJob(stage=key, script=path, depends_on=prev)) + prev = key + + label_st = slurm.stages.get("label") + shards = label_st.shards if label_st else None + for stage in enabled_stages(config): + if stage == "label" and shards and shards > 1: + # A job array of shard tasks (afterok on the array id waits for + # every element), then a small merge job publishing the artifact. + add("label", "label.sbatch", array=shards, + extra_args=f" --shard ${{SLURM_ARRAY_TASK_ID}}:{shards}") + add("label", "label-merge.sbatch", job_key="label_merge", + extra_args=" --merge-shards") + else: + add(stage, f"{stage}.sbatch") return jobs @@ -234,7 +268,11 @@ def _sbatch_chain( out = transport.run(cmd) job.job_id = prev_id = _parse_job_id(out.stdout) logger.info("submitted %s as job %s (after %s)", job.stage, job.job_id, job.depends_on) - log_event(ws.root, job.stage, "submitted", job_id=job.job_id, host=slurm.host) + # The merge job is bookkeeping for the label stage — attribute its + # submission there so status never shows a phantom "label_merge" stage. + stage = "label" if job.stage == "label_merge" else job.stage + extra = {"role": "merge"} if job.stage == "label_merge" else {} + log_event(ws.root, stage, "submitted", job_id=job.job_id, host=slurm.host, **extra) def submit( diff --git a/src/traincraft/orchestration/stages.py b/src/traincraft/orchestration/stages.py index 44d7fe5..3e41cdd 100644 --- a/src/traincraft/orchestration/stages.py +++ b/src/traincraft/orchestration/stages.py @@ -41,7 +41,7 @@ from ..core import Workspace from ..datasets import Dataset, read_frames, write_frames from ..geometry import build_geometries -from ..labeling import label_frames +from ..labeling import label_frames, merge_shard_labels from ..sampling import run_sampling from ..selection import run_funnel from ..state import log_event @@ -187,9 +187,9 @@ def _instrumented(fn): stage = fn.__name__.removeprefix("stage_") @functools.wraps(fn) - def wrapper(config, ws, force=False): + def wrapper(config, ws, force=False, **kwargs): try: - return fn(config, ws, force=force) + return fn(config, ws, force=force, **kwargs) except Exception as exc: _emit(ws, stage, "failed", error=f"{type(exc).__name__}: {exc}") raise @@ -269,8 +269,34 @@ def stage_select(config, ws, force=False): return selected +def label_shard(config, ws, shard: tuple[int, int]): + """One labeling shard: label frames ``[i::n]`` into its own journal dir. + + Deliberately *not* instrumented and writing no events, no ``labeled.extxyz`` + and no ``.key``: N shard tasks run concurrently and ``events.jsonl`` has a + single-writer contract — the shard's ``receipts.jsonl`` is its progress + record, and only the merge step publishes the stage artifact. + """ + if config.labeling is None: + raise ValueError("--shard needs a [labeling] section") + i, n = shard + if not 0 <= i < n: + raise ValueError(f"shard index {i} out of range for {n} shards") + # Round-robin split: DFT cost often trends along the trajectory, so + # contiguous chunks would load-balance badly. + frames = _latest_upstream(ws, "label")[i::n] + job = ws.job("labeled_dft", f"shard_{i:02d}") + logger.info("labeling shard %d/%d: %d frames -> %s", i, n, len(frames), job.dir) + return label_frames( + frames, + config.labeling.calculator, + out_dir=job.dir, + on_error=config.labeling.on_error, + ) + + @_instrumented -def stage_label(config, ws, force=False): +def stage_label(config, ws, force=False, merge_shards=False): if config.labeling is None: return _latest_upstream(ws, "label") out = _artifact_path(ws, "label") @@ -283,15 +309,20 @@ def stage_label(config, ws, force=False): frames = _latest_upstream(ws, "label") _emit(ws, "label", "start", n_in=len(frames)) t0 = time.perf_counter() - labeled = label_frames( - frames, - config.labeling.calculator, - out_dir=job.dir, - on_error=config.labeling.on_error, - ) + if merge_shards: + labeled, manifest = merge_shard_labels( + frames, config.labeling.calculator, out_dir=job.dir + ) + else: + labeled = label_frames( + frames, + config.labeling.calculator, + out_dir=job.dir, + on_error=config.labeling.on_error, + ) + manifest = json.loads((job.dir / "manifest.json").read_text()) write_frames(out, labeled) _write_key(out, key) - manifest = json.loads((job.dir / "manifest.json").read_text()) _emit(ws, "label", "done", n_frames=len(labeled), n_failed=manifest["n_failed"], n_reused=manifest["n_reused"], wall_seconds=round(time.perf_counter() - t0, 2), artifact=str(out)) @@ -401,11 +432,32 @@ def _validation_frames(config, ws) -> list: } -def run_stage(name: str, config, ws=None, *, force=False): - """Run a single named stage (seeding RNG so standalone runs are reproducible).""" +def run_stage( + name: str, + config, + ws=None, + *, + force=False, + shard: tuple[int, int] | None = None, + merge_shards: bool = False, +): + """Run a single named stage (seeding RNG so standalone runs are reproducible). + + ``shard=(i, n)`` labels the i-th of n frame shards into its own journal dir; + ``merge_shards`` assembles those shards into the stage artifact. Both apply + to the ``label`` stage only. + """ if name not in _DISPATCH: raise ValueError(f"unknown stage {name!r}; choose from {STAGE_ORDER}") + if (shard is not None or merge_shards) and name != "label": + raise ValueError("--shard/--merge-shards apply to the 'label' stage only") + if shard is not None and merge_shards: + raise ValueError("--shard and --merge-shards are mutually exclusive") ws = ws or workspace_for(config) if config.run.seed is not None: np.random.seed(config.run.seed) + if shard is not None: + return label_shard(config, ws, shard) + if merge_shards: + return stage_label(config, ws, force=force, merge_shards=True) return _DISPATCH[name](config, ws, force=force) diff --git a/tests/test_shard_label.py b/tests/test_shard_label.py new file mode 100644 index 0000000..ba7444d --- /dev/null +++ b/tests/test_shard_label.py @@ -0,0 +1,112 @@ +"""Sharded labeling: --shard I:N tasks + --merge-shards assembly.""" + +from __future__ import annotations + +import json + +import pytest + +from traincraft.config.models import ( + CrystalBuilder, + EmtCalc, + GeometryConfig, + LabelingConfig, + MdSampling, + RunConfig, + SelectionConfig, + TrainCraftConfig, +) +from traincraft.datasets.io import read_frames +from traincraft.orchestration.stages import run_stage +from traincraft.state import read_events + + +def _cfg(tmp_path, name): + return TrainCraftConfig( + run=RunConfig(name=name, outdir=str(tmp_path), seed=1), + geometry=GeometryConfig( + builder=CrystalBuilder( + name="Cu", crystalstructure="fcc", a=3.6, cubic=True, supercell=(2, 2, 2) + ) + ), + calculator=EmtCalc(), + sampling=MdSampling(temperature=300.0, steps=30, interval=10), + selection=SelectionConfig(budget=4), + labeling=LabelingConfig(calculator=EmtCalc()), + ) + + +def _prepare(tmp_path, name): + cfg = _cfg(tmp_path, name) + for s in ("geometry", "sample", "select"): + run_stage(s, cfg) + return cfg + + +def test_sharded_equals_serial(tmp_path): + serial = _prepare(tmp_path, "serial") + sharded = _prepare(tmp_path, "sharded") + + serial_frames = run_stage("label", serial) + + run_stage("label", sharded, shard=(0, 2)) + run_stage("label", sharded, shard=(1, 2)) + run_dir = tmp_path / "sharded" + # shard tasks publish nothing: no artifact, no .key, no label events + assert not (run_dir / "labeled_dft" / "labeled.extxyz").exists() + assert (run_dir / "labeled_dft" / "shard_00" / "done.extxyz").exists() + assert (run_dir / "labeled_dft" / "shard_01" / "receipts.jsonl").exists() + assert not [e for e in read_events(run_dir) if e["stage"] == "label"] + + merged = run_stage("label", sharded, merge_shards=True) + + assert len(merged) == len(serial_frames) + assert {s.hash for s in merged} == {s.hash for s in serial_frames} + for m, s in zip( + sorted(merged, key=lambda x: x.hash), + sorted(serial_frames, key=lambda x: x.hash), + strict=True, + ): + assert m.properties["energy"] == pytest.approx(s.properties["energy"]) + + # the merge publishes artifact + key + events, like a serial label run + out = run_dir / "labeled_dft" / "labeled.extxyz" + assert out.exists() and out.with_suffix(".extxyz.key").exists() + events = [e["event"] for e in read_events(run_dir) if e["stage"] == "label"] + assert events == ["start", "done"] + manifest = json.loads((run_dir / "labeled_dft" / "manifest.json").read_text()) + assert manifest["n_shards"] == 2 + assert manifest["n_failed"] == 0 + assert len(read_frames(out)) == len(serial_frames) + + +def test_missing_shard_becomes_failures_not_recompute(tmp_path): + cfg = _prepare(tmp_path, "gappy") + run_stage("label", cfg, shard=(0, 2)) # shard 1 never runs + + merged = run_stage("label", cfg, merge_shards=True) + manifest = json.loads((tmp_path / "gappy" / "labeled_dft" / "manifest.json").read_text()) + assert manifest["n_failed"] > 0 + assert manifest["n_failed"] + len(merged) == manifest["n_attempted"] + assert all("missing from every shard journal" in f["error"] for f in manifest["failures"]) + + +def test_shard_rerun_reuses_journal(tmp_path): + cfg = _prepare(tmp_path, "rerun") + run_stage("label", cfg, shard=(0, 2)) + run_stage("label", cfg, shard=(0, 2)) # e.g. a requeued array task + manifest = json.loads( + (tmp_path / "rerun" / "labeled_dft" / "shard_00" / "manifest.json").read_text() + ) + assert manifest["n_reused"] == manifest["n_attempted"] + assert manifest["n_failed"] == 0 + + +def test_shard_flags_are_label_only(tmp_path): + cfg = _prepare(tmp_path, "guard") + with pytest.raises(ValueError, match="label"): + run_stage("sample", cfg, shard=(0, 2)) + with pytest.raises(ValueError, match="mutually exclusive"): + run_stage("label", cfg, shard=(0, 2), merge_shards=True) + with pytest.raises(ValueError, match="out of range"): + run_stage("label", cfg, shard=(2, 2)) diff --git a/tests/test_slurm_executor.py b/tests/test_slurm_executor.py index 0894f4f..2c3ea87 100644 --- a/tests/test_slurm_executor.py +++ b/tests/test_slurm_executor.py @@ -90,6 +90,66 @@ def test_geometry_stage_defaults_to_core_image(tmp_path): assert "--nv" not in text # no GPU on the geometry stage +def _sharded_cfg(tmp_path, n=4): + cfg = _hpc_cfg(tmp_path) + cfg.orchestration.slurm.stages["label"] = SlurmStage( + partition="dcgp", nodes=2, ntasks=224, time="06:00:00", shards=n + ) + return cfg + + +def test_sharded_label_renders_array_plus_merge(tmp_path): + jobs = submit_slurm(_sharded_cfg(tmp_path), "myconfig.toml", dry_run=True) + assert [j.stage for j in jobs] == [ + "geometry", "sample", "select", "label", "label_merge", "dataset", + ] + assert [j.depends_on for j in jobs] == [ + None, "geometry", "sample", "select", "label", "label_merge", + ] + + label = (tmp_path / "hpc" / "slurm" / "label.sbatch").read_text() + assert "#SBATCH --array=0-3" in label + assert "label-%A_%a.out" in label # per-element logs + assert "--shard ${SLURM_ARRAY_TASK_ID}:4" in label + # each array task keeps the label stage's full DFT resources + injection + assert "#SBATCH --nodes=2" in label and "#SBATCH --ntasks=224" in label + assert "export TRAINCRAFT_AIMS_COMMAND=" in label + + merge = (tmp_path / "hpc" / "slurm" / "label-merge.sbatch").read_text() + assert "--merge-shards" in merge + assert "traincraft-core.sif" in merge # small assembly job, core image + assert "--array" not in merge + assert "#SBATCH --nodes=1" in merge + assert "TRAINCRAFT_AIMS_COMMAND" not in merge # merge never runs DFT + + +def test_merge_job_resources_overridable(tmp_path): + cfg = _sharded_cfg(tmp_path) + cfg.orchestration.slurm.stages["label_merge"] = SlurmStage( + partition="serial", time="00:20:00" + ) + submit_slurm(cfg, "myconfig.toml", dry_run=True) + merge = (tmp_path / "hpc" / "slurm" / "label-merge.sbatch").read_text() + assert "#SBATCH --partition=serial" in merge + assert "#SBATCH --time=00:20:00" in merge + + +def test_shards_on_non_label_stage_rejected(tmp_path): + import pytest + + cfg = _hpc_cfg(tmp_path) + cfg.orchestration.slurm.stages["sample"] = SlurmStage(shards=3) + with pytest.raises(ValueError, match="label stage only"): + submit_slurm(cfg, "myconfig.toml", dry_run=True) + + +def test_single_shard_renders_like_serial(tmp_path): + submit_slurm(_sharded_cfg(tmp_path, n=1), "myconfig.toml", dry_run=True) + label = (tmp_path / "hpc" / "slurm" / "label.sbatch").read_text() + assert "--array" not in label and "--shard" not in label + assert not (tmp_path / "hpc" / "slurm" / "label-merge.sbatch").exists() + + def _cray_native_cfg(tmp_path): """A Cray-style cluster (LUMI): native runtime, cray_shasta, no pmix/containers.""" return TrainCraftConfig( From 5ae5dfae7e3c54c946efac78b91df3cb3c3e2a0f Mon Sep 17 00:00:00 2001 From: David Abbasi Perez Date: Sun, 12 Jul 2026 07:44:44 +0200 Subject: [PATCH 14/15] fix(state,slurm): a new attempt clears a stage's stale error text, and the label_merge job stays out of the planned-stages list (found by live fake-cluster smoke test) Co-Authored-By: Claude Fable 5 Claude-Session: https://claude.ai/code/session_017RmprSjfXNtRV84X9cdkwS --- src/traincraft/orchestration/slurm.py | 6 ++++-- src/traincraft/state.py | 4 ++++ tests/test_remote_submit.py | 21 +++++++++++++++++++++ tests/test_state.py | 6 ++++-- 4 files changed, 33 insertions(+), 4 deletions(-) diff --git a/src/traincraft/orchestration/slurm.py b/src/traincraft/orchestration/slurm.py index fd87f17..8fbe235 100644 --- a/src/traincraft/orchestration/slurm.py +++ b/src/traincraft/orchestration/slurm.py @@ -308,7 +308,8 @@ def submit( log_event( ws.root, "run", "start", engine="slurm", - stages=[j.stage for j in jobs], + # the merge job is label-stage bookkeeping, not a planned stage + stages=[j.stage for j in jobs if j.stage != "label_merge"], jobs={j.stage: j.job_id for j in jobs}, ) return jobs @@ -355,7 +356,8 @@ def _submit_remote( log_event( ws.root, "run", "start", engine="slurm", - stages=[j.stage for j in jobs], + # the merge job is label-stage bookkeeping, not a planned stage + stages=[j.stage for j in jobs if j.stage != "label_merge"], jobs={j.stage: j.job_id for j in jobs}, host=slurm.host, remote_dir=remote_dir, diff --git a/src/traincraft/state.py b/src/traincraft/state.py index 261362f..8e9bd2d 100644 --- a/src/traincraft/state.py +++ b/src/traincraft/state.py @@ -133,6 +133,10 @@ def run_status(run_dir: str | Path) -> dict: # Accumulate, never replace: a "start" must not drop the job_id # recorded by an earlier "submitted" event. st = stages.setdefault(name, {}) + if ev in ("submitted", "start"): + # A new attempt supersedes an earlier failure of this stage. + st.pop("error", None) + st.pop("slurm_state", None) st.update(data) st["state"] = _STAGE_STATE[ev] if ev == "start": diff --git a/tests/test_remote_submit.py b/tests/test_remote_submit.py index 330b65a..4a2bd68 100644 --- a/tests/test_remote_submit.py +++ b/tests/test_remote_submit.py @@ -106,6 +106,27 @@ def test_remote_dry_run_renders_without_ssh(fake_bin, tmp_path, monkeypatch): assert "$MYSCRATCH/tcruns/rrun" in script # unresolved, for inspection only +def test_sharded_submit_keeps_merge_out_of_planned_stages(fake_bin, tmp_path, monkeypatch): + from traincraft.config.models import EmtCalc, LabelingConfig, SlurmStage + from traincraft.state import run_status + + cfg, _, mirror = _remote_cfg(tmp_path, monkeypatch) + cfg = cfg.model_copy(update={"labeling": LabelingConfig(calculator=EmtCalc())}) + cfg.orchestration.slurm.stages["label"] = SlurmStage(shards=2) + submit_slurm(cfg, "ignored.toml") + + events = read_events(mirror / "rrun") + run = [e for e in events if e["stage"] == "run"][0] + # the merge job is polled (jobs) but never planned (stages): a finished + # run must read "completed" without a phantom label_merge stage + assert "label_merge" in run["jobs"] + assert "label_merge" not in run["stages"] + sub = [e for e in events if e["event"] == "submitted"] + assert {e["stage"] for e in sub} == {"geometry", "label"} + assert [e.get("role") for e in sub if e["stage"] == "label"] == [None, "merge"] + assert "label_merge" not in run_status(mirror / "rrun")["stages"] + + def test_local_submit_still_uses_local_paths_and_gets_ids(fake_bin, tmp_path, monkeypatch): cfg, _, mirror = _remote_cfg(tmp_path, monkeypatch) local = cfg.model_copy( diff --git a/tests/test_state.py b/tests/test_state.py index efe8287..e1d6733 100644 --- a/tests/test_state.py +++ b/tests/test_state.py @@ -82,10 +82,12 @@ def test_run_status_failed_and_recovered(tmp_path): assert st["status"] == "failed" assert "boom" in st["stages"]["geometry"]["error"] - # a successful rerun supersedes the failure + # a successful rerun supersedes the failure — including its error text log_event(tmp_path, "geometry", "start") log_event(tmp_path, "geometry", "done", n_frames=1) - assert run_status(tmp_path)["status"] == "completed" + st = run_status(tmp_path) + assert st["status"] == "completed" + assert "error" not in st["stages"]["geometry"] def test_run_status_label_progress_from_receipts(tmp_path): From 1fe28bbca215a85b30ce4ca975439a8fcfcc112c Mon Sep 17 00:00:00 2001 From: David Abbasi Perez Date: Sun, 12 Jul 2026 07:44:44 +0200 Subject: [PATCH 15/15] =?UTF-8?q?docs:=20SSH-mode=20submission,=20traincra?= =?UTF-8?q?ft=20watch,=20sharded=20labeling=20=E2=80=94=20hpc=20how-to,=20?= =?UTF-8?q?config/cli=20reference,=20agent=20skill=20recipes,=20roadmap=20?= =?UTF-8?q?tick=20+=20multi-cluster=20follow-up?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Fable 5 Claude-Session: https://claude.ai/code/session_017RmprSjfXNtRV84X9cdkwS --- ROADMAP.md | 17 ++++++++ docs/how-to/hpc.md | 88 ++++++++++++++++++++++++++++++++++++++ docs/reference/cli.md | 30 +++++++++++++ docs/reference/config.md | 38 ++++++++++++++++ skills/traincraft/SKILL.md | 14 ++++++ 5 files changed, 187 insertions(+) diff --git a/ROADMAP.md b/ROADMAP.md index 4345820..f6c81a6 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -172,6 +172,23 @@ Deliverables aims.x`/`pw.x`. `traincraft submit CONFIG [--dry-run]`; `examples/19` (Leonardo, apptainer+pmix), `examples/20` (LUMI, native+cray_shasta). - ✅ Command-injection plumbing so `dft.py`/`mace` are container-agnostic. +- ✅ **SSH remote submission** — cluster profiles gained `host` (SSH alias) + + `remote_root`: `traincraft submit` works from a laptop/VM; the run lives at + `remote_root/` on the cluster (resolved config snapshot + input + files shipped), the local run dir is a mirror. The `Transport` seam + (`orchestration/transport.py`) is the future multi-cluster hook. +- ✅ **Job-state tracking + `traincraft watch`** — per-stage `submitted` events + with job ids (`status` shows `queued`); the watch loop polls `sacct`, ingests + remote events/receipts into the mirror, and records queue-level deaths + (OOM/timeout/cancel) the stage process never logged. Re-entrant, no daemon. +- ✅ **Sharded labeling** — `stages.label.shards = N` renders a Slurm job array + (`stage label --shard I:N`, per-shard single-writer journal dirs) + a merge + job (`--merge-shards`: assembles by fingerprint, never recomputes). Retry = + resubmit shards; execution-only config, never invalidates the label cache. +- 🔜 Multi-cluster routing (label on cluster A, train on cluster B) + rsync data + movement between clusters — per-stage `cluster =` referencing profiles, one + `Transport` per cluster, cross-cluster advance in the watch pass. PSI/J only + if a non-Slurm scheduler ever appears. - 🔜 DFT multi-node verified on a real cluster (PMIx launch + UCX transport on an IB cluster; `native`+cray-mpich on Cray). `TODO(site)` markers in the `.def`s for target-arch and the MKL link line. diff --git a/docs/how-to/hpc.md b/docs/how-to/hpc.md index 8e8130e..0bbd5fc 100644 --- a/docs/how-to/hpc.md +++ b/docs/how-to/hpc.md @@ -134,6 +134,91 @@ Any inline `[orchestration.slurm]` keys you add **override** the profile (handy for testing — e.g. drop `ntasks` while debugging), and inline per-stage tables deep-merge onto the profile's. The profile is the base; inline wins. +## Submit from your laptop or VM (SSH mode) + +Add two keys to the cluster profile and you no longer need to be on the login +node — `traincraft submit` reaches it over SSH: + +```toml +# ~/.traincraft/clusters/leonardo.toml +host = "leonardo" # SSH alias from ~/.ssh/config +remote_root = "$SCRATCH/traincraft-runs" # run dirs live here ON the cluster +# ... the rest of the profile as before +``` + +What happens at submit: + +1. `remote_root` is resolved **on the remote shell** (so `$SCRATCH`/`~` mean + the cluster's, never your laptop's) and `remote_root/` becomes the + run directory the jobs read and write. +2. A **resolved config snapshot** is shipped to `/config.toml`: the + profile is baked in (`profile`/`host`/`remote_root` stripped — remote jobs + are local to the cluster), and input files the config references + (`geometry.source.path`, `geometry.builder.file`, `validation.test_file`) + are copied to `/inputs/` and referenced relatively. Any *other* + file paths (e.g. `species[].file`, a custom model path) must already be + valid on the cluster. +3. The sbatch scripts are rendered with remote paths, pushed, and submitted + afterok-chained (with `--kill-on-invalid-dep=yes`, so a failed stage takes + its dependents down instead of leaving them pending forever). + +Your **local** run dir becomes a *mirror*: the rendered scripts, the shipped +snapshot (`config.remote.toml`), per-stage `submitted` events with job ids, and +whatever `traincraft watch` pulls back. `traincraft status`/`runs` work on it +unchanged. The remote run dir stays the source of truth for stage execution. + +SSH must be non-interactive (`BatchMode`): key-based auth that works without a +prompt. For frequent polling, connection multiplexing in `~/.ssh/config` avoids +a new handshake per command: + +``` +Host leonardo + ControlMaster auto + ControlPath ~/.ssh/cm-%r@%h:%p + ControlPersist 10m +``` + +## Watch a run + +```bash +traincraft watch my_run.toml # poll every 60 s until it finishes +traincraft watch runs/my_run --once # one refresh pass (exit 3 if ongoing) +``` + +Each pass pulls the remote `events.jsonl` + labeling receipts into the mirror, +polls `sacct` for every submitted job, and — crucially — records a `failed` +event for a job the **queue** killed (OOM, timeout, `scancel`, node failure) +that never got to log its own failure. Re-entrant and safe to interrupt: all +state lives in the run's event log. Requires `sacct` (Slurm accounting) on the +cluster. + +## Shard the label stage + +DFT labeling is embarrassingly parallel across frames. Turn the single label +job into a **job array** of N independent shard tasks plus a small merge job: + +```toml +[orchestration.slurm.stages.label] +partition = "dcgp_usr_prod" +nodes = 2 # per shard task — the full DFT allocation each +ntasks = 224 +shards = 8 # 8 array elements, frames dealt round-robin +``` + +Each task runs `traincraft stage label config.toml --shard I:8` into its own +`labeled_dft/shard_I/` (own scratch, receipts, resume journal — rerunning a +failed shard is incremental). The merge job then assembles the shard journals +into `labeled.extxyz`, recording frames no shard labeled as failures — it +never runs DFT itself. Retry failed frames by resubmitting the shards. +Shard count is pure execution config: changing it never invalidates the label +stage's cache. Live progress (`traincraft status` / `watch`) sums all shard +receipts. Merge-job resources are overridable via +`[orchestration.slurm.stages.label_merge]`. + +Pick the shard count from queue limits and DFT cost per frame: bigger shards +waste less queue time, smaller ones parallelize better and lose less work when +one dies. + ## Two knobs that make it portable: `runtime` and `mpi` There is **no universal MPI setup** — the cluster decides. TrainCraft exposes this @@ -180,6 +265,8 @@ Leonardo has a GPU **Booster** (A100) and a CPU **DCGP** partition, and ```toml [orchestration.slurm] account = "EUHPC_xxxxxxx" +host = "leonardo" # submit over ssh (drop to submit on-node) +remote_root = "$SCRATCH/traincraft-runs" runtime = "apptainer" mpi = "pmix" sif_dir = "$WORK/sif" @@ -195,6 +282,7 @@ gpus = 1 partition = "dcgp_usr_prod" nodes = 2 ntasks = 224 +shards = 8 # optional: label as an 8-task job array ``` Fill the `TODO(site)` markers in `containers/traincraft-dft.def` (target arch, MKL diff --git a/docs/reference/cli.md b/docs/reference/cli.md index 728745f..682d4a3 100644 --- a/docs/reference/cli.md +++ b/docs/reference/cli.md @@ -91,6 +91,8 @@ traincraft stage NAME CONFIG [--force] | `NAME` | One of: `geometry`, `sample`, `select`, `label`, `dataset`, `train`, `validate` | | `CONFIG` | Path to a `.toml` file | | `--force` | Recompute even if the stage's artifact already exists | +| `--shard I:N` | `label` only: this task labels the I-th of N frame shards into `labeled_dft/shard_I/` (what a `shards = N` job array runs per element) | +| `--merge-shards` | `label` only: assemble the shard journals into `labeled.extxyz` (never recomputes; missing frames are recorded as failures) | **Example — train on a dataset you already built:** @@ -127,6 +129,34 @@ The GPU stages (`sample`, `train`, `validate`) run in `traincraft-mlip.sif` with `--nv`; the DFT `label` stage injects the engine command. See [Run on HPC](../how-to/hpc.md). +When the cluster profile sets `host` (an SSH alias), submission happens **over +ssh from wherever you are**: the run dir is created at `remote_root/` +on the cluster, a resolved config snapshot plus the input files are shipped +there, and the local run dir becomes a mirror holding the rendered scripts and +submission events. Follow the run with [`traincraft watch`](#traincraft-watch). + +--- + +## `traincraft watch` + +Follow a submitted Slurm run until it finishes. Each pass polls the scheduler +(`sacct`, over ssh in remote mode), pulls the run's remote `events.jsonl` and +labeling receipts into the local mirror, and records queue-level deaths (OOM, +timeout, cancellation) that the stage process never got to log — so +`traincraft status` never lies about a job the queue killed. Re-entrant: +Ctrl-C and rerun any time. + +```bash +traincraft watch CONFIG_OR_RUN_DIR [--interval 60] [--once] +``` + +| Option | Description | +|---|---| +| `--interval` | Seconds between polls (default 60) | +| `--once` | One pass: refresh state, print it, exit | + +Exit code: `0` completed, `1` failed, `3` still in progress (only with `--once`). + --- ## `traincraft runs` diff --git a/docs/reference/config.md b/docs/reference/config.md index c0ac028..5531a98 100644 --- a/docs/reference/config.md +++ b/docs/reference/config.md @@ -633,3 +633,41 @@ thresholds = { forces_rmse = 0.05, energy_mae_per_atom = 0.005 } A frame whose energy/forces prediction fails is skipped and recorded (same philosophy as `[labeling]`'s `on_error="skip"`); optional properties the model cannot produce are dropped per property without voiding the frame. + +--- + +## `[orchestration]` + +How the pipeline executes — `local` (default, in-process) or `slurm` +(each stage a dependency-chained batch job). Full guide: +[Run on HPC](../how-to/hpc.md). + +```toml +[orchestration] +engine = "slurm" + +[orchestration.slurm] +profile = "leonardo" # base: ~/.traincraft/clusters/leonardo.toml (inline keys win) +host = "leonardo" # SSH alias → submit/monitor from your laptop or VM +remote_root = "$SCRATCH/traincraft-runs" # run dir root on the cluster (expands remotely) + +[orchestration.slurm.stages.label] +partition = "dcgp_usr_prod" +nodes = 2 +ntasks = 224 +shards = 8 # label as a job array of 8 shard tasks + a merge job +``` + +| Field | Default | Meaning | +|---|---|---| +| `profile` | — | Saved cluster profile used as the base config | +| `host` | — | SSH alias of the login node; unset = you are already on it | +| `remote_root` | — | Base dir for run dirs on the cluster (required with `host`); `$VAR`/`~` expand on the *remote* shell | +| `account`, `runtime`, `mpi`, `sif_dir`, `modules`, `binds`, … | | See [Run on HPC](../how-to/hpc.md) | +| `stages..*` | | Per-stage resources (`partition`, `nodes`, `ntasks`, `gpus`, `time`, `mem`, `image`, …) | +| `stages.label.shards` | — | Split labeling into N array tasks (each with the label stage's resources) plus a merge job; execution-only — never invalidates the label cache | +| `stages.label_merge.*` | 1 node, core image | Resources for the merge job | + +With `host` set, the local run dir is a **mirror**: submission events, rendered +scripts, and state pulled by [`traincraft watch`](cli.md#traincraft-watch). The +cluster's run dir at `remote_root/` is where the jobs read and write. diff --git a/skills/traincraft/SKILL.md b/skills/traincraft/SKILL.md index 53757a7..7699e49 100644 --- a/skills/traincraft/SKILL.md +++ b/skills/traincraft/SKILL.md @@ -126,6 +126,17 @@ Map the user's words to config keys (run `traincraft plugins` for the live list) variants (stochastic builders get derived seeds); `smiles` with `n_conformers > 1` and `file` with `index = ":"` also yield several seeds. Every seed is sampled and the candidates pooled before selection. +- **HPC from here (SSH mode):** if the cluster profile + (`~/.traincraft/clusters/.toml`) has `host` (SSH alias) + + `remote_root`, `traincraft submit` works from this machine: the run lives at + `remote_root/` on the cluster, the local run dir is a mirror. + Follow with `traincraft watch [--once]` (also catches jobs the + queue killed: OOM/timeout). Status may show stages as `queued`. +- **Sharded DFT labeling:** set `shards = N` on + `[orchestration.slurm.stages.label]` → label runs as an N-task job array + (round-robin frames, per-shard resume journals) + a merge job. Retry failed + frames by resubmitting; the journals make reruns incremental. Changing + `shards` never invalidates the label cache. ## 📂 Outputs (under `runs//`) @@ -169,6 +180,9 @@ traincraft validate # validate + show resolved stages pixi run -e traincraft run # run the pipeline pixi run -e traincraft stage # one stage standalone # (geometry|sample|select|label|dataset|train|validate) +traincraft submit [--dry-run] # Slurm: render + submit dependency-chained jobs + # (over ssh when the profile sets `host`) +traincraft watch [--once] # follow a submitted run; exit 0/1/3 traincraft runs [outdir] [--json] # list all runs + status (default outdir: runs/) traincraft status [--json] # per-stage status of one run (live label progress) ```