Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
15 commits
Select commit Hold shift + click to select a range
e648f48
feat(labeling): per-frame failure isolation (on_error skip/raise), qu…
basillicus Jul 7, 2026
cf1c881
feat(validation): parity metrics + thresholded quality_report.json as…
basillicus Jul 7, 2026
330dc45
docs: teach the skill, CLI/API reference, examples (26) and tutorials…
basillicus Jul 7, 2026
17151c9
feat(labeling): replace per-frame directories with append-only receip…
basillicus Jul 7, 2026
1991265
feat(state): run-state layer — per-run events.jsonl + lazy SQLite ind…
basillicus Jul 7, 2026
be9e8cb
feat(service): HTTP (FastAPI) + MCP service over the run-state layer
basillicus Jul 7, 2026
9a32536
polish(cli): rich help with workflow-grouped command panels and per-c…
basillicus Jul 7, 2026
9e9daad
feat(geometry): multi-structure spine — build_geometries, [geometry] …
basillicus Jul 10, 2026
a48e281
feat(state): submitted/queued job events — accumulate-on-start fold, …
basillicus Jul 11, 2026
0f208f6
feat(orchestration): Transport seam — run/shell/push/pull locally or …
basillicus Jul 11, 2026
252c33e
feat(slurm): SSH remote submission — host/remote_root on profiles, re…
basillicus Jul 11, 2026
06296b4
feat(watch): traincraft watch — sacct polling with array aggregation,…
basillicus Jul 11, 2026
8054d42
feat(label): sharded labeling — stage --shard I:N / --merge-shards, S…
basillicus Jul 11, 2026
5ae5dfa
fix(state,slurm): a new attempt clears a stage's stale error text, an…
basillicus Jul 12, 2026
1fe28bb
docs: SSH-mode submission, traincraft watch, sharded labeling — hpc h…
basillicus Jul 12, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
72 changes: 65 additions & 7 deletions ROADMAP.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -161,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/<run.name>` 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.
Expand Down Expand Up @@ -216,15 +244,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.

---

Expand All @@ -249,6 +290,23 @@ 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 (`<outdir>/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.

### ✅ 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.
Expand Down
2 changes: 1 addition & 1 deletion docs/concepts/architecture.md
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand Down
27 changes: 23 additions & 4 deletions docs/concepts/calculators.md
Original file line number Diff line number Diff line change
Expand Up @@ -117,13 +117,32 @@ 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
frame_0000/ … # per-frame work dirs (so file-IO calcs don't collide)
manifest.json # level of theory, property set, counts (attempted/failed/reused), failures
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 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 <run-dir>` 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.
8 changes: 7 additions & 1 deletion docs/concepts/training.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -33,6 +33,12 @@ labelled frames) and writes a model tree under `runs/<name>/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
Expand Down
2 changes: 1 addition & 1 deletion docs/getting-started/end-to-end.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
84 changes: 84 additions & 0 deletions docs/how-to/agent-service.md
Original file line number Diff line number Diff line change
@@ -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 `<run>/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.
88 changes: 88 additions & 0 deletions docs/how-to/hpc.md
Original file line number Diff line number Diff line change
Expand Up @@ -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/<run.name>` becomes the
run directory the jobs read and write.
2. A **resolved config snapshot** is shipped to `<run dir>/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 `<run dir>/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
Expand Down Expand Up @@ -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"
Expand All @@ -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
Expand Down
1 change: 1 addition & 0 deletions docs/how-to/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
9 changes: 5 additions & 4 deletions docs/how-to/own-mace-model.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Loading
Loading