diff --git a/packs/catalog.json b/packs/catalog.json new file mode 100644 index 0000000..dc0483c --- /dev/null +++ b/packs/catalog.json @@ -0,0 +1,104 @@ +{ + "packs": [ + { + "name": "speedrun", + "version": "0.2.0", + "description": "single-metric script/benchmark optimization under a wall-clock budget: setup, optimize, measure, report; no paper", + "description_zh": "墙钟预算内的单指标脚本/基准优化:搭建、优化、测量、报告;不写论文", + "requires": [], + "needs": [ + "Python 3.10+; bundled evidence check uses only the standard library and needs no GPU. Optimization runs need the task's frozen scorer, inputs, benchmark software and declared hardware; the NanoGPT trace specifically needs its original 8xH100 harness and software. Nothing is installed or detected by this pack." + ], + "files": [ + { + "path": "LICENSE", + "size": 1109 + }, + { + "path": "SKILL.md", + "size": 6623 + }, + { + "path": "evidence.py", + "size": 3173 + }, + { + "path": "skills/engineer/speedrun-hands-on-trace.md", + "size": 16931 + }, + { + "path": "skills/engineer/speedrun-sota-optimization.md", + "size": 26198 + } + ] + }, + { + "name": "materials", + "version": "0.2.0", + "description": "materials science and materials processing across atomistic, microstructure, continuum, CAD/CAE, and experimental scales", + "description_zh": "材料科学与材料加工,跨原子、微观组织、连续介质、CAD/CAE 与实验尺度", + "requires": [], + "needs": [ + "Python 3.10+; evidence.py uses only the standard library and needs no GPU. Scientific execution needs task-selected data, solver or instrument access, licenses and hardware, and authorization for physical work. Nothing is installed or detected by this pack." + ], + "files": [ + { + "path": "LICENSE", + "size": 1109 + }, + { + "path": "SKILL.md", + "size": 10664 + }, + { + "path": "evidence.py", + "size": 4463 + }, + { + "path": "skills/engineer/materials-atomistic-simulation.md", + "size": 2707 + }, + { + "path": "skills/engineer/materials-cad-cae-process-simulation.md", + "size": 3216 + }, + { + "path": "skills/engineer/materials-data-literature-grounding.md", + "size": 2020 + }, + { + "path": "skills/engineer/materials-ecosystem-routing.md", + "size": 3554 + }, + { + "path": "skills/engineer/materials-experiment-loop.md", + "size": 1975 + }, + { + "path": "skills/engineer/materials-research-execution.md", + "size": 2065 + }, + { + "path": "skills/manager/materials-research-manager.md", + "size": 1458 + }, + { + "path": "skills/planner/materials-research-planning.md", + "size": 2106 + }, + { + "path": "skills/reviewer/materials-research-review.md", + "size": 2283 + }, + { + "path": "skills/reviewer/materials-simulation-signoff.md", + "size": 2283 + }, + { + "path": "skills/reviewer/materials-validation-review.md", + "size": 2053 + } + ] + } + ] +} diff --git a/packs/materials/LICENSE b/packs/materials/LICENSE new file mode 100644 index 0000000..4c02d79 --- /dev/null +++ b/packs/materials/LICENSE @@ -0,0 +1,22 @@ +MIT License + +Copyright (c) 2026 lbx154 +Copyright (c) 2026 Argus AI Team contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/packs/materials/SKILL.md b/packs/materials/SKILL.md new file mode 100644 index 0000000..e3711b6 --- /dev/null +++ b/packs/materials/SKILL.md @@ -0,0 +1,145 @@ +--- +name: materials +description: "materials science and materials processing across atomistic, microstructure, continuum, CAD/CAE, and experimental scales" +version: 0.2.0 +--- + +# materials + +materials science and materials processing across atomistic, microstructure, continuum, CAD/CAE, and experimental scales. + +## What counts as done + +### scope + +- **scope.material-system** — The material composition, phase or microstructure, processing or service state, relevant environment, and observables are explicit. + Evidence hint: the actual material system, state, environment, and measured outputs + +- **scope.scale-regime** — The relevant spatial and temporal scales and physical regime are identified, so an electronic, atomistic, mesoscale, continuum, process, data-driven, or experimental route can be chosen for physical reasons. + Evidence hint: a justified scale/regime choice and the phenomena it retains or omits + +- **scope.success-criterion** — Success is checkable and matches the request: explanation, calibrated model, property prediction, validated process design, reproduced result, new finding, or an honest bounded negative result. + Evidence hint: a task-specific observable, comparator, tolerance, or decision criterion + +- **scope.physical-safety** — If the route includes physical synthesis, processing, testing, or instrument operation, the authorized personnel, approved procedure, hazards, interlocks, required controls, and waste handling are established before execution; simulation-only work marks this item not applicable. + Evidence hint: applicable laboratory/process authorization and controls, or a simulation-only rationale + +### grounding + +- **grounding.primary-sources** — Claims about prior materials, mechanisms, models, and measurements are grounded in resolvable primary sources or authoritative databases at the evidence level actually available. + Evidence hint: primary papers, standards, database records, or public datasets read directly + +- **grounding.baseline-gap** — The strongest relevant baseline and closest prior work are identified, and any novelty or improvement claim states the exact difference rather than relying on a generic literature gap. + Evidence hint: a direct comparison with the strongest applicable prior result + +- **grounding.data-tools-access** — Data provenance, licenses, material-property sources, solver availability, compute, and experimental access are checked before the plan depends on them. + Evidence hint: real access evidence and explicit constraints for data, software, compute, and lab equipment + +### model + +- **model.physics-and-units** — The governing physics, variables, equations, units, parameter sources, assumptions, and validity range are explicit and dimensionally consistent. + Evidence hint: the implemented model and parameter values with units and provenance + +- **model.material-state** — Material behavior reflects the relevant composition, phase, temperature, strain rate, texture, defects, microstructure, and processing history rather than an unjustified generic material card. + Evidence hint: material-state inputs and the evidence supporting each important dependency + +- **model.discretization-boundaries** — Geometry, periodic cell or CAD model, discretization, interactions or contact, boundary/initial conditions, loads, ensembles, and solver controls match the physical question. + Evidence hint: actual model inputs plus an explanation of the chosen boundaries and discretization + +- **model.calibration-validation-split** — Parameters fitted or selected from data are separated from validation evidence; the evaluation does not reuse its target as an input or tune on hidden answers. + Evidence hint: a declared calibration/selection set and an independent validation set or oracle + +### execute + +- **execute.real-run** — The claimed calculation or experiment actually ran. Generated scripts, input decks, GUI screenshots, or submitted jobs alone are not solver or instrument results. + Evidence hint: native outputs, logs, job identity, timestamps, and parsed observables from a completed run + +- **execute.reproducible-provenance** — Inputs, structures or CAD, material parameters, pseudopotentials or force fields, mesh, software and versions, seeds, hardware, commands, and output files are preserved to the level needed to reproduce the claim. + Evidence hint: the exact executable path, versioned inputs, run command, environment, and native outputs + +- **execute.health-failures** — Solver or experiment health is inspected during execution; divergence, non-convergence, unstable dynamics, distorted elements, unphysical states, instrument faults, and failed attempts remain visible and are not relabeled as data. + Evidence hint: diagnostics and retained failure evidence alongside accepted runs + +- **execute.capability-boundary** — Unavailable licenses, software, hardware, samples, or instruments produce an explicit statement of what is missing or a clearly labeled surrogate, never a fabricated run. + Evidence hint: real capability discovery and an honest boundary for anything not run + +- **execute.physical-safety-compliance** — Any physical experiment or processing run stayed within its authorization, approved procedure, equipment interlocks, and material-handling and disposal controls; non-physical work states that this is not applicable. + Evidence hint: run-specific authorization and safety records, or a non-physical execution rationale + +### validate + +- **validate.numerical-convergence** — Numerical claims are supported by convergence or stability checks appropriate to the method: mesh/time step/cell size, k-points/cutoff, sampling duration, optimizer tolerance, or another justified control. + Evidence hint: fresh convergence or stability results over the parameters that can change the conclusion + +- **validate.physical-consistency** — Units, conservation laws, symmetries, limiting cases, monotonic trends, bounds, and known physical behavior are checked where applicable. + Evidence hint: independent physical sanity checks tied to the actual observables + +- **validate.independent-reference** — Headline results are compared like-for-like against an independent analytic result, public benchmark, trusted implementation, published measurement, or new physical experiment under matching conditions. + Evidence hint: raw comparison data with matched material state, geometry, conditions, and metric + +- **validate.sensitivity-uncertainty** — Important parameter, model-form, stochastic, and measurement uncertainties are tested or bounded, and conclusions are no stronger than their robustness. + Evidence hint: sensitivity or uncertainty results for the assumptions that could reverse the claim + +- **validate.integrity** — The evaluation is independent of optimization and protected against leakage, hard-coded known outputs, edited references, selective run deletion, and comparison across mismatched hardware, conditions, or metrics. + Evidence hint: a frozen evaluator or protocol plus complete raw attempts and like-for-like baselines + +### report + +- **report.claim-evidence** — Every main claim points to actual calculations, raw data, figures, tables, literature, or experimental records, and the evidence supports its stated scope. + Evidence hint: claim-by-claim traceability to inspectable evidence + +- **report.simulation-experiment-boundary** — Predicted, simulated, surrogate, and experimentally measured quantities are distinguished explicitly; a digital result is not described as physical validation. + Evidence hint: clear labels for each evidence type and any missing real-world validation + +- **report.reproducibility-limitations** — The delivered result records reproduction instructions, material and process conditions, software or instrument details, uncertainty, negative results, known limitations, and the domain where the conclusion applies. + Evidence hint: a proportional report or paper plus runnable inputs and retained raw evidence + +## Run the checks + +Run from the project workspace; replace `` with this pack's absolute directory: + +```sh +python3 '/evidence.py' --help +python3 '/evidence.py' check --project-root . --stage execute +python3 '/evidence.py' check --project-root . --stage validate +python3 '/evidence.py' check --project-root . --stage report +``` + +Create project `research/MATERIALS_EVIDENCE.json` with `version: 1` and a non-empty `evidence` list of `{kind, path}` entries. Paths must be unique, project-relative, contained, existing non-empty files. The allowed kinds and per-check requirements are in [evidence.py](evidence.py). `execute` needs native output, run log, analysis, experimental record, or blocker; `validate` needs validation or blocker; `report` needs report plus both preceding groups. Exit 0 confirms a structurally valid index; exit 1 prints each issue. A blocker can document a bounded negative result; neither a passing index nor job completion proves scientific success. Inspect native evidence and the checks above independently. + +## Needs + +Python 3.10+; evidence.py uses only the standard library and needs no GPU. Scientific execution needs task-selected data, solver or instrument access, licenses and hardware, and authorization for physical work. Nothing is installed or detected by this pack. + +## Role references + +Each entry is a bundled file; project output paths within the references are created by the task. + +- engineer: [materials-atomistic-simulation.md](skills/engineer/materials-atomistic-simulation.md) + +- engineer: [materials-cad-cae-process-simulation.md](skills/engineer/materials-cad-cae-process-simulation.md) + +- engineer: [materials-data-literature-grounding.md](skills/engineer/materials-data-literature-grounding.md) + +- engineer: [materials-ecosystem-routing.md](skills/engineer/materials-ecosystem-routing.md) + +- engineer: [materials-experiment-loop.md](skills/engineer/materials-experiment-loop.md) + +- engineer: [materials-research-execution.md](skills/engineer/materials-research-execution.md) + +- manager: [materials-research-manager.md](skills/manager/materials-research-manager.md) + +- planner: [materials-research-planning.md](skills/planner/materials-research-planning.md) + +- reviewer: [materials-research-review.md](skills/reviewer/materials-research-review.md) + +- reviewer: [materials-simulation-signoff.md](skills/reviewer/materials-simulation-signoff.md) + +- reviewer: [materials-validation-review.md](skills/reviewer/materials-validation-review.md) + + +## Supporting files + +- [LICENSE](LICENSE) + +- [evidence.py](evidence.py) diff --git a/packs/materials/evidence.py b/packs/materials/evidence.py new file mode 100644 index 0000000..e88fa78 --- /dev/null +++ b/packs/materials/evidence.py @@ -0,0 +1,121 @@ +"""Structural evidence index for materials execution, validation, and reports.""" +from __future__ import annotations + +import argparse +import json +import sys +from pathlib import Path + +EVIDENCE_RELPATH = Path("research/MATERIALS_EVIDENCE.json") +EVIDENCE_KINDS = frozenset({ + "source", + "input", + "code", + "native_output", + "run_log", + "analysis", + "experimental_record", + "validation", + "report", + "blocker", + "safety_record", +}) +_REQUIRED_KINDS = { + "execute": ({"native_output", "run_log", "analysis", "experimental_record", "blocker"},), + "validate": ({"validation", "blocker"},), + "report": ( + {"report"}, + {"native_output", "run_log", "analysis", "experimental_record", "blocker"}, + {"validation", "blocker"}, + ), +} + + +def _inside(root: Path, candidate: Path) -> bool: + try: + candidate.relative_to(root) + return True + except ValueError: + return False + + +def validate_evidence(project_root: object, stage: str) -> list[str]: + """Validate indexed evidence paths without judging scientific content.""" + root = Path(str(project_root or ".")).resolve() + stage_name = (stage or "").strip().lower() + if stage_name not in _REQUIRED_KINDS: + return [f"unsupported materials evidence stage: {stage_name!r}"] + manifest = root / EVIDENCE_RELPATH + try: + payload = json.loads(manifest.read_text(encoding="utf-8")) + except FileNotFoundError: + return [f"missing {EVIDENCE_RELPATH.as_posix()}"] + except (OSError, json.JSONDecodeError) as exc: + return [f"invalid {EVIDENCE_RELPATH.as_posix()}: {exc}"] + if not isinstance(payload, dict) or payload.get("version") != 1: + return [f"{EVIDENCE_RELPATH.as_posix()} must declare version 1"] + entries = payload.get("evidence") + if not isinstance(entries, list) or not entries: + return [f"{EVIDENCE_RELPATH.as_posix()} must contain a non-empty evidence list"] + + issues: list[str] = [] + present_kinds: set[str] = set() + seen_paths: set[str] = set() + for index, entry in enumerate(entries): + if not isinstance(entry, dict): + issues.append(f"evidence[{index}] must be an object") + continue + kind = str(entry.get("kind") or "").strip().lower() + relpath = str(entry.get("path") or "").strip() + if kind not in EVIDENCE_KINDS: + issues.append(f"evidence[{index}] has unsupported kind {kind!r}") + else: + present_kinds.add(kind) + if not relpath: + issues.append(f"evidence[{index}] has no path") + continue + if relpath in seen_paths: + issues.append(f"evidence[{index}] repeats path {relpath!r}") + continue + seen_paths.add(relpath) + raw_path = Path(relpath) + if raw_path.is_absolute() or ".." in raw_path.parts: + issues.append(f"evidence[{index}] path must stay project-relative: {relpath!r}") + continue + try: + candidate = (root / raw_path).resolve(strict=True) + except OSError: + issues.append(f"evidence[{index}] path does not exist: {relpath!r}") + continue + if not _inside(root, candidate): + issues.append(f"evidence[{index}] path escapes the project: {relpath!r}") + elif not candidate.is_file(): + issues.append(f"evidence[{index}] path is not a file: {relpath!r}") + elif candidate.stat().st_size <= 0: + issues.append(f"evidence[{index}] path is empty: {relpath!r}") + + for accepted in _REQUIRED_KINDS[stage_name]: + if not present_kinds.intersection(accepted): + issues.append( + f"{stage_name} requires evidence kind in: {', '.join(sorted(accepted))}" + ) + return issues + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(prog="materials-evidence") + parser.add_argument("command", choices=["check"], nargs="?", default="check") + parser.add_argument("--project-root", default=".") + parser.add_argument("--stage", choices=sorted(_REQUIRED_KINDS), required=True) + args = parser.parse_args(argv) + issues = validate_evidence(args.project_root, args.stage) + if issues: + for issue in issues: + print(f"ERROR: {issue}", file=sys.stderr) + return 1 + print(f"materials evidence valid for {args.stage}") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) \ No newline at end of file diff --git a/packs/materials/skills/engineer/materials-atomistic-simulation.md b/packs/materials/skills/engineer/materials-atomistic-simulation.md new file mode 100644 index 0000000..a52bc08 --- /dev/null +++ b/packs/materials/skills/engineer/materials-atomistic-simulation.md @@ -0,0 +1,49 @@ +--- +name: "Materials Atomistic Simulation" +description: "Run provenance-preserving DFT, ML interatomic-potential, molecular-dynamics, phonon, defect, diffusion, and stability studies with scale-appropriate convergence and validation." +--- + +# Materials Atomistic Simulation + +## Route selection + +- Use electronic-structure calculations when the claim depends on bonding, + charge, magnetic or electronic state, reaction energetics, or reference labels. +- Use classical or ML interatomic potentials for larger systems and longer + trajectories only after checking that the potential covers the relevant + elements, phases, configurations, energies, forces, and stresses. +- Use an installed Quantum ESPRESSO, ABACUS, or licensed VASP for DFT only after + inspecting its local version, pseudopotentials, and project execution path. +- Use atomate2/jobflow or AiiDA for durable multi-job workflows when available. + AtomisticSkills provides reusable tool/skill patterns; MatClaw demonstrates a + code-first HPC route. Argus remains responsible for planning and review. + +## Execution contract + +1. Preserve the exact initial structure, cell, species, occupancies, charge, + magnetic initialization, and any defects or interfaces. +2. Record code/version, pseudopotential or basis identity, exchange-correlation + functional, dispersion treatment, cutoff, k-point mesh, smearing, electronic + and ionic tolerances, spin settings, and hardware. +3. For MD, record the potential/model revision, ensemble, thermostat/barostat, + time step, equilibration, production length, seeds, sampling interval, and + initial-condition generation. +4. Store native outputs and parse them without discarding warnings or failed + electronic/ionic steps. +5. Check convergence of every parameter capable of changing the conclusion. + Relaxation convergence alone is not property convergence. +6. Check cell-size, sampling-time, finite-temperature, and finite-size effects + where they matter. Report statistical uncertainty from independent samples or + defensible correlation analysis. +7. Validate against analytic limits, higher-fidelity calculations, trusted + implementations, OpenKIM tests, public benchmark data, or matched experiments. + +## Automatic claim downgrades + +- A potential outside its training/validation domain supports an exploratory + result, not a reliable material prediction. +- A short stable trajectory is not evidence of long-time thermodynamic stability. +- A 0 K perfect-crystal result is not a room-temperature processed-material result. +- Formation energy alone does not establish synthesizability. +- Agreement between two tools sharing the same model assumptions is not fully + independent validation. diff --git a/packs/materials/skills/engineer/materials-cad-cae-process-simulation.md b/packs/materials/skills/engineer/materials-cad-cae-process-simulation.md new file mode 100644 index 0000000..7dba5d8 --- /dev/null +++ b/packs/materials/skills/engineer/materials-cad-cae-process-simulation.md @@ -0,0 +1,73 @@ +--- +name: "Materials CAD CAE and Process Simulation" +description: "Build and validate parameterized geometry, meshes, constitutive models, contacts, thermal-mechanical loads, and solver workflows for material behavior and manufacturing processes." +--- + +# Materials CAD, CAE, and Process Simulation + +## Tool route + +- For headless parameterized geometry, prefer build123d/CadQuery; use FreeCAD or + a commercial CAD API when feature coverage or existing assemblies require it. +- Use Gmsh or the solver-native mesher and retain mesh-quality statistics. +- Open routes include CalculiX, FEniCSx, and MOOSE. Licensed routes may use + Abaqus scripting, PyAnsys, COMSOL Java/MPh, or DEFORM's Python API. +- CAE-Agent-Hub, AbaqusAgent, and sim-cli are useful adapter and failure-recovery + references. Do not delegate scientific judgment to them. + +## Geometry and mesh + +1. Parameterize dimensions that the research question may change. Preserve the + source model and export a solid format such as STEP when appropriate; STL is + not a parametric solid model. +2. Verify topology, units, bounding box, volume, interfaces, contact surfaces, + and orientation before meshing. +3. Choose element type, order, integration, local refinement, contact + discretization, and quality limits for the expected deformation, thermal + gradients, incompressibility, fracture, or localization. +4. Perform mesh-convergence or discretization-error analysis on the observables + used in claims, not only on element count. + +## Material and process model + +1. Tie every material card or user subroutine to composition, phase, temperature, + strain rate, processing history, and calibration data. State isotropy, + anisotropy, hardening, rate, thermal, damage, fracture, creep, and phase-change + assumptions. +2. Keep calibration and validation cases separate. A constitutive fit reproducing + its own calibration curve is not independent validation. +3. Define contact, friction, heat transfer, tooling, constraints, loads, + amplitudes, boundary/initial conditions, and process sequence from the real + setup. +4. For forming, machining, additive, heat-treatment, or joining simulations, + check mass/energy behavior, remeshing or element deletion, distortion, + temperature history, state transfer, and path dependence. + +## Solver loop + +Use bounded, inspectable steps: + +```text +detect/version/license +-> create or import geometry +-> validate geometry +-> mesh and inspect quality +-> assign material/process model +-> apply interactions and BC/IC +-> lint or data-check +-> solve +-> inspect status and native diagnostics +-> extract observables +-> preserve native outputs +``` + +Classify failures as geometry, mesh, material, interaction, BC/load, convergence, +license, or postprocessing errors. Repair the implicated stage and rerun its +checks; do not blindly regenerate the whole model. + +## Evidence boundary + +A `.inp`, Workbench project, or DEFORM database proves only model construction. +A completed job proves only execution. For the claim to hold scientifically you +additionally need convergence, physical sanity, sensitivity, and comparison +under matched conditions. Never report a GUI image as the sole evidence for a numerical value. diff --git a/packs/materials/skills/engineer/materials-data-literature-grounding.md b/packs/materials/skills/engineer/materials-data-literature-grounding.md new file mode 100644 index 0000000..ce2ab52 --- /dev/null +++ b/packs/materials/skills/engineer/materials-data-literature-grounding.md @@ -0,0 +1,38 @@ +--- +name: "Materials Data and Literature Grounding" +description: "Ground material identity, properties, mechanisms, baselines, and novelty in resolvable primary literature and provenance-preserving public databases." +--- + +# Materials Data and Literature Grounding + +## Operating method + +1. Normalize the material identity before searching: composition, phase, + polymorph, structure, defects, microstructure, processing history, + temperature, pressure, and other state variables that affect the property. +2. Search primary papers and authoritative databases. Use reviews to navigate, + then verify claim-critical facts in the original source. +3. For database records, retain provider, material or structure identifier, + query/filter, retrieval date, calculation provenance, units, and any license + or access condition. +4. Distinguish measured values, first-principles calculations, empirical + potentials, ML predictions, and values copied from another compilation. +5. Compare only matched conditions. A room-temperature polycrystal measurement + is not a clean oracle for a 0 K single-crystal calculation without a stated + model connecting them. +6. Identify the strongest relevant baseline and closest prior method. If novelty + matters, state the exact known/new boundary; otherwise leave novelty unknown. +7. Preserve missingness and disagreement. Do not average incompatible phases, + units, processing histories, or measurement methods into a convenient target. + +## Useful interfaces + +- Materials Project `mp-api` and pymatgen for structures and computed properties; +- OPTIMADE for cross-provider structure queries; +- NOMAD for calculation provenance and archived simulations; +- OpenKIM and ColabFit for interatomic models and reference datasets; +- domain repositories and standards appropriate to the actual material class. + +Database values are inputs or comparison evidence, not automatic ground truth. +Check how each value was calculated or measured before using it to calibrate or +validate a model. diff --git a/packs/materials/skills/engineer/materials-ecosystem-routing.md b/packs/materials/skills/engineer/materials-ecosystem-routing.md new file mode 100644 index 0000000..19bc2f1 --- /dev/null +++ b/packs/materials/skills/engineer/materials-ecosystem-routing.md @@ -0,0 +1,67 @@ +--- +name: "Materials Tool and Skill Router" +description: "Select and connect the appropriate open or licensed materials database, atomistic, CAD, CAE, workflow, and evaluation tools without replacing Argus's four-role control loop." +--- + +# Materials Tool and Skill Router + +Use this skill after the scientific scale and observable are understood. The +projects below are capability surfaces, not authorities about which research +question to pursue. + +## Route by scientific scale + +| Need | Preferred capability surface | +| --- | --- | +| structures and computed properties | Materials Project `mp-api`, OPTIMADE, NOMAD, pymatgen | +| structure manipulation and calculators | ASE | +| composable atomistic skills | AtomisticSkills | +| code-first remote/HPC computation | MatClaw patterns, jobflow-remote | +| provenance-aware workflows | atomate2/jobflow or AiiDA | +| DFT | Quantum ESPRESSO, ABACUS, or an installed licensed VASP | +| MD and interatomic models | LAMMPS, ASE, OpenKIM, MACE/MatGL/FAIRChem | +| parametric CAD | build123d-mcp, CadQuery, FreeCAD, or an installed commercial CAD API | +| mesh | Gmsh or the selected solver's native mesher | +| open continuum/FEM | CalculiX, FEniCSx, or MOOSE | +| commercial CAE | Abaqus, PyAnsys, COMSOL API, or DEFORM Python API when licensed | +| solver-neutral execution | sim-cli plugins or a small project-native driver | +| evaluator | public experiments, Matbench Discovery, OpenKIM tests, or a task-specific frozen protocol | + +## Integration rules + +1. Reuse Argus Manager, Planner, Engineer, and Reviewer. Do not launch an + external autonomous agent as an unreviewed second planner. +2. Inspect the installed version and local documentation before calling an API. + Do not guess solver object names or silently fall back to GUI clicking. +3. Prefer typed APIs and solver-native batch commands. For a live session, use + bounded steps: detect, connect, inspect, execute, inspect, checkpoint, export. +4. Keep data-query tools read-only and separate from code-execution or HPC + submission tools. Restrict workspaces and credentials. +5. Do not install or copy proprietary SDKs. Open adapters do not grant a solver + license. +6. Audit third-party MCP servers before enabling arbitrary Python, Java, shell, + or network execution. Bind local services to a trusted interface only. +7. If no suitable integration is installed, write the smallest project-local + adapter around the official API rather than screen-scraping the GUI. + +## Upstream projects to inspect at the installed revision + +- AtomisticSkills: https://github.com/learningmatter-mit/AtomisticSkills +- MatClaw: https://github.com/cz2014/MatClaw +- Materials Project API: https://github.com/materialsproject/api +- ASE: https://gitlab.com/ase/ase +- atomate2: https://github.com/materialsproject/atomate2 +- AiiDA: https://github.com/aiidateam/aiida-core +- LAMMPS: https://github.com/lammps/lammps +- Quantum ESPRESSO: https://github.com/QEF/q-e +- OpenKIM: https://openkim.org/ +- build123d-mcp: https://github.com/pzfreo/build123d-mcp +- CadQuery MCP: https://github.com/CadQuery/cadquery-contrib/tree/master/mcp-server +- CAE-Agent-Hub: https://github.com/Cai-aa/CAE-Agent-Hub +- sim-cli: https://github.com/svd-ai-lab/sim-cli +- AbaqusAgent: https://github.com/LIRAM-LIN/AbaqusAgent +- PyAnsys: https://docs.pyansys.com/ +- DEFORM API announcement: https://www.deform.com/2025/04/11/spring-2025-deform-news/ + +These links document available interfaces. Their presence here does not certify +a particular commit, scientific result, license, or local installation. diff --git a/packs/materials/skills/engineer/materials-experiment-loop.md b/packs/materials/skills/engineer/materials-experiment-loop.md new file mode 100644 index 0000000..642cbde --- /dev/null +++ b/packs/materials/skills/engineer/materials-experiment-loop.md @@ -0,0 +1,39 @@ +--- +name: "Materials Experiment Loop" +description: "Design or operate a materials experiment loop with explicit samples, instruments, controls, safety boundaries, provenance, calibration, and simulation-to-experiment comparison." +--- + +# Materials Experiment Loop + +Use this skill for physical synthesis, processing, characterization, or +mechanical testing. A-Lab and Coscientist demonstrate useful closed-loop +patterns, but Argus may claim a physical experiment only when it has real, +authorized instrument or laboratory access and native records. + +## Before execution + +1. Define sample identity, provenance, batch, geometry, preparation, processing + history, storage, and environmental controls. +2. Define the observable, instrument, calibration, resolution, detection limit, + controls, replicates, randomization, and exclusion policy before seeing the + desired answer. +3. Separate exploration from confirmatory validation. Reserve independent + samples or conditions for the claim that matters. +4. Respect laboratory safety, equipment interlocks, authorization, and material + handling rules. Never let a language-model action bypass an existing safety + control. + +## During and after execution + +- Record instrument identity, software/version, calibration, operator/agent + action, timestamps, raw files, sample mapping, environmental conditions, and + every failed or excluded run. +- Monitor instrument faults and out-of-range states. Do not convert a fault, + saturation, missing peak, or corrupted file into a scientific observation. +- Analyze raw data with uncertainty and appropriate controls. Preserve the + transformation from raw signal to reported quantity. +- Compare simulation and experiment under matched geometry, material state, + loading, temperature, rate, and measurement definition. +- If no instrument was available, deliver an experiment design or simulation + prediction labeled as such; never imply that a sample was synthesized or + measured. diff --git a/packs/materials/skills/engineer/materials-research-execution.md b/packs/materials/skills/engineer/materials-research-execution.md new file mode 100644 index 0000000..96a9ea3 --- /dev/null +++ b/packs/materials/skills/engineer/materials-research-execution.md @@ -0,0 +1,35 @@ +--- +name: "Materials Research Execution" +description: "Execute materials research with scale-appropriate models, real tools, explicit units and material state, reproducible provenance, and honest capability boundaries." +--- + +# Materials Research Execution + +MISSION TYPE: MATERIALS RESEARCH. Work on the real material, processing path, +microstructure, environment, and observables named by the task. Select the +electronic, atomistic, mesoscale, continuum, data, or experimental route from +the physics; do not run every available method. + +Inspect project instructions and existing environments before installing or +choosing tools. Use official APIs and native batch interfaces when available. +Treat MCP servers and generated Python as execution surfaces, not evidence. +Evidence begins with a completed solver or instrument run and its native output. +Index the evidence actually used in `research/MATERIALS_EVIDENCE.json` (version +1, `evidence` list of project-relative `path` + `kind`). This is a provenance +index, not a substitute for the native files or a scientific conclusion. + +Make composition, phase, temperature, pressure, strain rate, texture, defects, +processing history, geometry, units, model parameters, boundary/initial +conditions, and validity range explicit where they matter. Preserve exact +inputs, software versions, seeds, commands, raw outputs, failures, and hardware +or instrument context. + +Never infer scientific success from job completion alone. Inspect convergence, +stability, conservation, element/cell quality, and physical trends. Separate +fitted data from validation data. Do not describe a surrogate or simulation as +an experiment, a generated input as a run, or a missing commercial license as +a successful calculation. Physical work must remain inside the authorized +procedure, equipment interlocks, and applicable handling and disposal controls; +do not bypass them. Return an honest bounded result, naming what is missing, when the required +data, compute, solver, sample, instrument, authorization, or safety controls are +unavailable. diff --git a/packs/materials/skills/manager/materials-research-manager.md b/packs/materials/skills/manager/materials-research-manager.md new file mode 100644 index 0000000..cc092d0 --- /dev/null +++ b/packs/materials/skills/manager/materials-research-manager.md @@ -0,0 +1,26 @@ +--- +name: "Materials Research Manager Context" +description: "Route materials-science and materials-processing work through the four-role Argus system while preserving the real material, scale, and requested research outcome." +--- + +# Materials Research Manager Context + +MISSION TYPE: MATERIALS RESEARCH. This vertical covers material composition, +structure, defects, microstructure, processing, properties, degradation, and +service behavior across electronic, atomistic, mesoscale, continuum, and +experimental scales. + +Preserve the operator's actual goal. Select this vertical when the central +unknown is about a material or material-processing system, even if the work also +uses physics, CAD, optimization, software, or a research paper. Do not route a +pure solver installation or repository repair here when its outcome is only +software delivery. + +You are the front door and stage authority in the four-role system. Keep the six +broad stages `scope`, `grounding`, `model`, `execute`, `validate`, and `report`, +but do not prescribe which scientific methods must run. The Planner chooses the +scale and route, the Engineer performs the work, and the independent Reviewer +judges the evidence. A bounded reproduction, calibrated model, or negative result +may close its experiment when that is the honest answer; it does not complete the +research objective unless the Reviewer judges it valuable. A generated input deck +or unconverged solver run is not a result. diff --git a/packs/materials/skills/planner/materials-research-planning.md b/packs/materials/skills/planner/materials-research-planning.md new file mode 100644 index 0000000..9e9e3dc --- /dev/null +++ b/packs/materials/skills/planner/materials-research-planning.md @@ -0,0 +1,37 @@ +--- +name: "Materials Research Planning" +description: "Plan materials research by selecting the physical scale, evidence source, toolchain, baseline, and validation route that resolve the current scientific uncertainty." +--- + +# Materials Research Planning + +Plan from the material system and unresolved scientific question, not from a +fixed software menu. Own the scale and route decision: first determine which +scales and observables control the claim. Choose only the methods needed: + +- primary literature and public materials data; +- electronic-structure or atomistic calculation; +- ML interatomic potential, molecular dynamics, or mesoscale simulation; +- constitutive modeling, CAD, meshing, FEM, or process simulation; +- statistical/data-driven analysis; +- physical experiment design or execution when real instruments are available. + +Inspect the actual repository, installed software, licenses, data access, +compute, and instrument access before depending on them. Prefer public, +reproducible inputs and a real evaluation protocol. A commercial solver is a +valid route only when its license and executable/API are genuinely available; +otherwise choose a scientifically defensible open route or report the missing +capability. Before planning physical synthesis, processing, testing, or +instrument operation, confirm the authorized personnel, approved procedure, +hazards, equipment interlocks, required controls, and waste-handling path. + +For every planned claim, identify a like-for-like baseline or independent +validation source and the checks that could falsify it. Separate calibration +from validation. Include convergence, sensitivity, uncertainty, and physical +sanity work in proportion to the conclusion, not as generic paperwork. + +Use the strongest existing tool layer rather than building another agent +harness. AtomisticSkills, MatClaw, CAE-Agent-Hub, sim-cli, and CAD MCP projects +are capability references or adapters; Argus remains the Planner. Schedule +bounded tasks that produce inspectable scientific evidence, retain failed +attempts, and change route when evidence invalidates the plan. diff --git a/packs/materials/skills/reviewer/materials-research-review.md b/packs/materials/skills/reviewer/materials-research-review.md new file mode 100644 index 0000000..64ba58d --- /dev/null +++ b/packs/materials/skills/reviewer/materials-research-review.md @@ -0,0 +1,42 @@ +--- +name: "Materials Research Review" +description: "Independently review materials research for system fidelity, literature grounding, physical validity, evidence strength, reproducibility, and calibrated claims." +--- + +# Materials Research Review + +MISSION TYPE: MATERIALS RESEARCH. Review the material result, not the amount of +workflow paperwork. Argus has four persistent roles; you are the independent +Reviewer and do not replace the Manager's stage authority or the Planner's +forward plan. + +Read the original objective and identify the material, state, scale, environment, +processing or service conditions, observables, and requested completion bar. +Then inspect the actual sources, inputs, code, native solver/instrument outputs, +comparisons, and final claims. Use `research/MATERIALS_EVIDENCE.json` only to +locate them; an entry in the index is not evidence of correctness. + +Require: + +- faithful material-system and scale selection; +- primary-source and database provenance at the evidence level actually read; +- model parameters, units, assumptions, boundaries, and validity range; +- a real completed calculation or experiment for every execution claim; +- independent validation, convergence, sensitivity, and uncertainty + proportional to the conclusion; +- like-for-like baselines and a clean calibration/validation boundary; +- reproducible inputs and raw outputs, including failed attempts; +- explicit separation of prediction, simulation, surrogate, and measurement. +- for physical work, authorization plus applicable approved procedures, + interlocks, hazard controls, material handling, and waste disposal. + +Reject solver completion as scientific validation, a fitted curve as an +independent test, a perfect-crystal result as a processed bulk-material result, +an inaccessible paper as read evidence, and a generated CAD/input deck as an +executed study. Reject physical work that bypassed authorization or safety +controls. Reject novelty claims without direct prior-work comparison. + +Return `done` only when the result meets the requested bar and every headline +claim is supported within a stated regime. Otherwise return `continue` with the +single highest-value repair, `replan_requested` when the direction should change, +or `blocked` with the exact missing capability. diff --git a/packs/materials/skills/reviewer/materials-simulation-signoff.md b/packs/materials/skills/reviewer/materials-simulation-signoff.md new file mode 100644 index 0000000..e9e4fb6 --- /dev/null +++ b/packs/materials/skills/reviewer/materials-simulation-signoff.md @@ -0,0 +1,37 @@ +--- +name: "Materials Simulation Evidence Review" +description: "Read atomistic, continuum, CAD/CAE, and process simulations from their native inputs and outputs — material state, discretization, solver health, convergence, and claim fidelity — before trusting the result." +--- + +# Materials Simulation Evidence Review + +## Review protocol + +1. Reconstruct what was actually simulated: material identity/state, geometry or + cell, governing model, parameter sources, loads, boundary/initial conditions, + interactions, numerical controls, and requested observable. +2. Inspect native inputs and outputs. Confirm solver version, job identity, exit + status, warnings, iterations or increments, and the exact files used for + postprocessing. +3. For electronic/atomistic work, inspect structure, pseudopotential/basis or + force-field/model identity, convergence controls, cell/k-point/cutoff or + sampling/time-step choices, ensemble, equilibration, and finite-size effects. +4. For continuum/process work, inspect CAD units/topology, mesh and element + choice, contact, material law and calibration range, large-deformation or + thermal coupling settings, distortion/remeshing/deletion, and state transfer. +5. Rerun a bounded critical check when practical. Compare extracted values with + the native result rather than trusting a report or screenshot. +6. Require convergence and physical checks on claim-critical observables. + Agreement at one discretization or a green solver icon is insufficient. +7. Compare against an independent result under matched conditions and inspect + sensitivity to assumptions capable of reversing the conclusion. +## Automatic rejection conditions + +- input deck, generated script, submitted job, or screenshot presented as a result; +- unconverged electronic structure, unstable MD, failed increment, excessive + element distortion, or ignored fatal warning; +- material properties used outside their temperature/rate/phase/calibration range; +- calibration data reused as independent validation; +- missing units or mismatched geometry, loading, temperature, rate, or metric; +- stale output, manually edited result, selective deletion, or undocumented rerun; +- commercial solver or instrument result claimed without real access and native evidence. diff --git a/packs/materials/skills/reviewer/materials-validation-review.md b/packs/materials/skills/reviewer/materials-validation-review.md new file mode 100644 index 0000000..a16ee91 --- /dev/null +++ b/packs/materials/skills/reviewer/materials-validation-review.md @@ -0,0 +1,43 @@ +--- +name: "Materials Validation Review" +description: "Independently validate materials claims through convergence, physical invariants, sensitivity, uncertainty, matched baselines, public benchmarks, and experimental evidence." +--- + +# Materials Validation Review + +Validation must be capable of falsifying the result. Choose checks from the +method and claim rather than requiring the same packet for every task. + +## Numerical validity + +- inspect mesh, time-step, cell-size, k-point, cutoff, trajectory-length, + sampling, optimizer, and tolerance convergence where relevant; +- check conservation, symmetry, dimensional consistency, limiting cases, known + trends, and physically admissible ranges; +- verify that postprocessing definitions match the reported observable; +- assess stochastic variability and correlation rather than reporting one seed + or trajectory as exact. + +## Model validity + +- verify material composition, phase, microstructure, temperature, rate, + environment, and processing history; +- identify extrapolation beyond constitutive, potential, surrogate, or + measurement calibration; +- test sensitivity to assumptions and model forms capable of changing the claim; +- distinguish agreement caused by shared assumptions from independent evidence. + +## External validity and integrity + +- compare with an analytic result, trusted implementation, public benchmark, + published measurement, or new experiment under matched conditions; +- keep evaluator/reference data frozen and separate from optimization; +- inspect all relevant attempts, not only the selected successful run; +- reject hard-coded outputs, edited references, target leakage, mismatched + hardware/conditions/metrics, and unsupported cherry-picking; +- calibrate the conclusion to supported, partial, inconclusive, or unknown. + +Do not demand physical experiments for a claim explicitly bounded to a +simulation method, but do require the report to say that experimental validity +remains unestablished. Conversely, do not call a simulation-only match an +experimental discovery. diff --git a/packs/speedrun/LICENSE b/packs/speedrun/LICENSE new file mode 100644 index 0000000..4c02d79 --- /dev/null +++ b/packs/speedrun/LICENSE @@ -0,0 +1,22 @@ +MIT License + +Copyright (c) 2026 lbx154 +Copyright (c) 2026 Argus AI Team contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/packs/speedrun/SKILL.md b/packs/speedrun/SKILL.md new file mode 100644 index 0000000..7ce6861 --- /dev/null +++ b/packs/speedrun/SKILL.md @@ -0,0 +1,69 @@ +--- +name: speedrun +description: "single-metric script/benchmark optimization under a wall-clock budget: setup, optimize, measure, report; no paper" +version: 0.2.0 +--- + +# speedrun + +single-metric script/benchmark optimization under a wall-clock budget: setup, optimize, measure, report; no paper. + +## What counts as done + +### setup + +- **setup.solution_self_contained** — What the mission asks for is the EDITABLE file it names (a recipe / solution file / kernel) that uses the mission's FROZEN harness/scorer UNCHANGED and modifies ONLY that editable file. The reviewer must confirm the agent did NOT touch the harness, the evaluation, the metric, the held-out data, or the budget — they are byte-identical to the scaffold (`git diff` or a byte comparison against the pinned scaffold) — and that the candidate is scored through the mission's frozen scorer exactly as the mission specifies. + Evidence hint: the editable file + an empty harness `git diff` vs the pinned scaffold + a run log produced through the mission's frozen scorer + +- **setup.heldout_val** — Evaluation reads the HELD-OUT / contract-specified inputs wired by the frozen harness, and there is NO leakage or exploit: the candidate does not see, memorise, or HARDCODE the known eval inputs/answers, and the metric / eval inputs are the scaffold's, untouched. The reward must reflect genuine generalisation, so a candidate that obtains its score by encoding the known eval distribution (e.g. baking in fixed statistics of the test inputs) rather than COMPUTING the real result is disqualified — that is a reward hack, not a result. + Evidence hint: the harness's eval wiring + the candidate showing it COMPUTES the real result rather than encoding/hardcoding the known eval inputs + +### optimize + +- **optimize.metric_curve** — The mission metric over the run MOVES THE RIGHT WAY (the candidate is actually improving within the budget), OR any flat / wrong-way / noisy / early-plateau trajectory is EXPLICITLY explained (e.g. budget-bound, schedule, warmup, divergence) rather than silently accepted. A trajectory that never improves over the starting point is a dead attempt, not a result. No real trajectory means this item is UNSATISFIED: an external launch rejection may justify a blocked mission, but never optimize-stage completion. + Evidence hint: the metric-vs-step (or vs-wall-clock) series in the run log; a one-line explanation for any non-improving trajectory + +### measure + +- **measure.repeat_mean_metric** — The reported result is the AGGREGATE mission metric across N repeats (iterate at small N, report the final number at higher N) — NOT a single lucky run and NEVER the number the candidate printed about itself. A per-repeat record captures each run's metric as RE-MEASURED by the VERIFIER re-running the candidate through the frozen scorer under the identical protocol; the headline the reviewer trusts is the verifier's, because the agent edits only the editable file and can self-report anything. + Evidence hint: per-repeat record (run, metric) from the verifier's re-runs + the computed aggregate; each row traceable to a real frozen-scorer output line + +- **measure.budget_respected** — Every scored run respected the FIXED budget the mission declares (wall-clock and hardware) — the candidate did not extend, bypass, or hand-tune the budget, and no scored run exceeded it. The contest is the BEST metric reachable UNDER the fixed budget, so a candidate that only attains its score by exceeding the budget is invalid; the budget in the frozen harness stays unchanged. + Evidence hint: per-run wall-clock within the declared budget in the run log / manifest; the budget in the frozen harness unchanged + +### report + +- **report.beats_baseline** — The proposed candidate's metric BEATS the RE-MEASURED baseline: the named reference baseline re-run ON OUR harness and hardware under the identical protocol (same repeats, same budget, same held-out eval) — NOT a published number from different hardware. The comparison is head-to-head and cites BOTH per-run records (ours and the re-measured baseline's) so the win is a like-for-like delta, not a measurement artifact of differing hardware or protocol. If the candidate does NOT beat the re-measured baseline, say so plainly and queue a repair/pivot — do not relabel a loss as a win. + Evidence hint: two per-run records (proposed vs re-measured baseline) under the identical protocol + the metric delta; baseline re-run on our hardware, not a published number from other hardware + +## Run the checks + +Run from the project workspace; replace `` with this pack's absolute directory: + +```sh +python3 '/evidence.py' --help +python3 '/evidence.py' speedrun --project-root . +``` + +The check finds `attempts/**/results.csv` or `experiments/**/results.csv` with at least one finite value in `val_bpb`, `mean_val_bpb`, `seconds_to_target`, `wall_seconds`, `score`, or `metric_value`. Exit 0 prints the accepted file; exit 1 means evidence is absent or invalid. It checks structure, not scientific validity, repeat count, provenance, budget compliance, or a baseline win. For another mission metric, record its value in `metric_value` as well as the task's original field. A final report also needs a non-empty project `RESULTS.md` and the repeat/baseline evidence described above; inspect these separately. + +Run optimization and measurement with the frozen scorer supplied by the task. The commands and files in the two role references are a historical NanoGPT example, not bundled executables: `eval_solution.sh`, `analyze_sweep.py`, `solution/`, `research/`, and `experiments/` belong to that benchmark/project. Replace example paths, versions and hardware only as the task's protocol permits. The two companion references link to each other inside this pack; single-kernel procedures mentioned as a different use case must come from the task. + +## Needs + +Python 3.10+; bundled evidence check uses only the standard library and needs no GPU. Optimization runs need the task's frozen scorer, inputs, benchmark software and declared hardware; the NanoGPT trace specifically needs its original 8xH100 harness and software. Nothing is installed or detected by this pack. + +## Role references + +Each entry is a bundled file; project output paths within the references are created by the task. + +- engineer: [speedrun-hands-on-trace.md](skills/engineer/speedrun-hands-on-trace.md) + +- engineer: [speedrun-sota-optimization.md](skills/engineer/speedrun-sota-optimization.md) + + +## Supporting files + +- [LICENSE](LICENSE) + +- [evidence.py](evidence.py) diff --git a/packs/speedrun/evidence.py b/packs/speedrun/evidence.py new file mode 100644 index 0000000..031b4bd --- /dev/null +++ b/packs/speedrun/evidence.py @@ -0,0 +1,106 @@ +"""Standalone speedrun structural evidence check, adapted from Argus metric_evidence.""" + + +from __future__ import annotations + + +import argparse +import csv +import math +import sys +from pathlib import Path + + +class EvidenceError(ValueError): + """Raised when no trustworthy scored row is present.""" + + +_SPEEDRUN_METRICS = { + "val_bpb", + "mean_val_bpb", + "seconds_to_target", + "wall_seconds", + "score", + "metric_value", +} + + +def _finite_number(value: object) -> float | None: + try: + number = float(str(value).strip()) + except ValueError: + return None + return number if math.isfinite(number) else None + + +def _csv_rows(path: Path) -> tuple[set[str], list[dict[str, str]]]: + try: + with path.open("r", encoding="utf-8-sig", newline="") as handle: + reader = csv.DictReader(handle) + fields = {str(name or "").strip().lower() for name in (reader.fieldnames or [])} + rows = [ + {str(key or "").strip().lower(): str(value or "").strip() for key, value in row.items()} + for row in reader + ] + except (OSError, csv.Error) as exc: + raise EvidenceError(f"{path}: unreadable CSV: {exc}") from exc + return fields, rows + + +def _candidate_csvs(project_root: Path, pattern: str) -> list[Path]: + root = project_root.resolve() + paths: set[Path] = set() + for rel in ("attempts", "experiments"): + base = root / rel + if base.is_dir(): + paths.update( + path + for path in base.rglob(pattern) + if _is_contained_file(root, path) + ) + return sorted(paths) + + +def _is_contained_file(project_root: Path, path: Path) -> bool: + root = project_root.resolve() + try: + resolved = path.resolve(strict=True) + except OSError: + return False + return resolved.is_relative_to(root) and resolved.is_file() + + +def validate_speedrun_evidence(project_root: Path) -> Path: + """Return a results CSV containing at least one finite metric value.""" + for path in _candidate_csvs(project_root, "results.csv"): + fields, rows = _csv_rows(path) + metric_fields = fields & _SPEEDRUN_METRICS + if metric_fields and any( + _finite_number(row.get(field)) is not None + for row in rows + for field in metric_fields + ): + return path + raise EvidenceError( + "no attempts/**/results.csv or experiments/**/results.csv contains a " + f"finite metric column ({', '.join(sorted(_SPEEDRUN_METRICS))})" + ) + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(prog="speedrun-evidence") + parser.add_argument("kind", choices=["speedrun"]) + parser.add_argument("--project-root", default=".") + args = parser.parse_args(argv) + root = Path(args.project_root).resolve() + try: + path = validate_speedrun_evidence(root) + except EvidenceError as exc: + print(f"FAIL: {exc}", file=sys.stderr) + return 1 + print(f"OK: structured metric evidence in {path.relative_to(root)}") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/packs/speedrun/skills/engineer/speedrun-hands-on-trace.md b/packs/speedrun/skills/engineer/speedrun-hands-on-trace.md new file mode 100644 index 0000000..e8fdd27 --- /dev/null +++ b/packs/speedrun/skills/engineer/speedrun-hands-on-trace.md @@ -0,0 +1,267 @@ +--- +name: "Speedrun Hands-on Trace" +description: "A worked NanoGPT-speedrun trace on 8xH100, written as the operator's own known-good procedure: search first, then the exact commands, the line-cited recipe knobs chosen by lever class, the measured convergence curve, and the decision at each fork — recorded as a causal chain of measure, decompose, pick the binding lever, change one thing, re-measure, bank. The agent's own live run took the wrong path, and that path is kept as the counterexample." +--- + +## Title +Speedrun Hands-on Trace + +## Description +A **human-written seed exemplar** of how to optimize a training-speedrun benchmark +(minimize wall-clock to a fixed quality target under a statistical validity rule). It is +written deliberately as the **known-good operating procedure** — the concrete commands and +recipe knobs I would actually run, with the decision at each fork — *not* a transcript of +the agent's live run (that run nibbled a single mechanism family for hours and is recorded +below only as the **nails** — what not to do). The spine is a per-candidate **measured +causal chain** where every step is bound to a real number from the frozen scorer, every +knob is line-cited from the live recipe, and the next move follows from **the binding +constraint** — which on this task is *convergence at the tail*, and at certification time +is *statistical power*, not recipe quality. When a real run teaches a sharper chain, evolve +this. + +## When to use +- The task is a wall-clock training-speedrun to a fixed metric target (e.g. modded-nanogpt + `val_loss <= 3.28`) with a frozen scorer and a **statistical validity rule** (a t-test + over N runs), on real GPUs (8xH100 / B200). +- The agent must produce real `train_time` / `val_loss` / `p` numbers and record the + measure → decompose → pick-lever → re-measure → bank loop. +- A speedrun is stuck nibbling: many mechanisms tried, floor not moving, a quality-valid + near-win sitting un-certified. + +## When NOT to use +- You only need the high-level methodology and toolkit. Use [Speedrun SOTA Optimization](speedrun-sota-optimization.md). +- The task is a single GPU kernel (use the task's single-kernel procedure), a paper matrix, or an + RL/post-training run. +- The scorer is unavailable and the user explicitly asks you not to attempt recovery. + +## The one rule this trace exists to teach + +> **Attack the biggest lever, not the most fun one — and a faster number is not a result +> until the t-test certifies it.** On a near-SOTA training recipe the per-step kernels are +> already near the roofline; the leverage is in **fewer steps to the target** (convergence), +> which compounds. And when a candidate's mean is already inside the target, the binding +> constraint is *sample size*, not your recipe — you certify (N=10), you do not re-engineer. +> The live run violated both halves: it spent hours on per-step FP8/MLP precision while the +> optimizer/schedule went untouched, and it kept building mechanisms on a recipe that was +> already valid at N=10. That cost ~3 hours and ~6 missions. +> +> **And a rule precedes even this: you are knowledge-limited, so RETRIEVE before you build.** +> Reciting a lever from memory (as the FIRST draft of this trace did — "add SGLD / leaner MLP") +> gets its coefficients and conditions wrong; you go read the concrete prior art and reproduce +> it. Invention here is *disciplined recombination of retrieved, reproduced knowledge*, not +> recall — see [Speedrun SOTA Optimization](speedrun-sota-optimization.md) §0. (Anti-cheat: general technique only, never this +> task's answer key.) + +## What "process data" means here — the chain to learn + +Record each candidate as one linked block. Learn the shape; it is a teaching exemplar, not +a rigid form a harness greps for: + +```text +CAND + command: + measured: train_time=±sd over N=; val_loss=±sd; + p(mean<3.28)= -> VALID/INVALID + decompose: steps × per_step (instantaneous, by stage); convergence: val_loss@steps + (where does the curve cross the target?) + read: faster/slower? quality in or out? if INVALID -> QUALITY (mean>target) or + POWER (mean<` — ships `solution/{train.py,triton_kernels.py}` to 8xH100 +through the manifest's remote command and frozen interpreter (torch 2.10+cu128 / triton +3.6 / FA3), runs `torchrun --nproc_per_node=8` N times, `analyze_sweep.py` runs the one-sided +t-test `t=(mean-3.28)/(sd/√n)`, prints `SCORE valid= n= val_loss=±sd +p(mean<3.28)=

train_time=±sd s`. `valid` iff `p<0.01`. Iterate at N=3, certify at N=10. +Target `val_loss<=3.28`, minimize `train_time`. Anchors (8xH100): #83 official 79.7s; our #83 +re-measure 80.18s; automated frontier (Recursive) 77.3s. + +Initialize `$NANOGPT_REMOTE`, `$NANOGPT_BENCH_ROOT`, `$NANOGPT_DATA_ROOT`, +and `$NANOGPT_PYTHON` from the mission manifest before using the commands +below. A missing value is an infrastructure problem to report, not a value to guess. + +### OP 0 — SEARCH the literature, reproduce the anchor, extract the curve + +Before any edit I retrieve human knowledge first — I am knowledge-limited and reciting levers +from memory gets them wrong (general technique ONLY; searching this task's leaderboard/answer +is disqualifying). The concrete searches, and what each is FOR: + +```text +# the concrete source for each lever I might pull (arxiv/repo, not my memory of it): +WebSearch "Muon optimizer Newton-Schulz Moonlight RMS-match AdamW weight decay" +WebSearch "warmup-stable-decay WSD cooldown fraction" ; "muP muTransfer LR transfer small proxy" +WebSearch "RHO-loss reducible holdout online batch selection" ; "sequence length warmup curriculum" +WebSearch "FP8 training delayed scaling SwiGLU outlier instability Transformer Engine" +WebSearch "Fantastic Pretraining Optimizers equal tuning speedup at scale" # treat every N× as an UPPER bound +# the diagnostic method, so I self-measure the bottleneck instead of guessing: +WebSearch "GPU roofline MFU 6N per token nsys torch.profiler per-step breakdown" +``` + +I keep the most CONCRETE form (coefficients, ablation conditions), corroborate any "N× faster" +against a second source, and treat it as a hypothesis to reproduce — not a fact. THEN reproduce +the anchor on our own box and read the real curve: + +```bash +cd "$NANOGPT_BENCH_ROOT" +./eval_solution.sh solution 3 # reproduce the #83 seed on OUR box +grep -E 'step:[0-9]+/1385 val_loss:' experiments//run_1.txt # extract the curve +``` + +```text +CAND seed #83 — baseline (no edits) + measured: train_time=80.18s±0.06 (N=3), val_loss=3.2774±0.0004, p(mean<3.28)=0.00341 -> VALID + decompose: the REAL convergence curve (mean over 3 runs), with instantaneous per-step: + step val_loss cum_time per-step(this segment) + 0 10.830 0.00 s — + 250 4.463 7.99 s 32.0 ms (Stage 1: batch 131072, seq 896) + 500 4.148 16.97 s 35.9 ms + 750 3.735 31.33 s 57.5 ms (Stage 2: batch 262144, seq 2048) + 1000 3.460 47.89 s 66.2 ms + 1250 3.331 68.83 s 83.8 ms (Stage 3: batch 393216, seq 2048) + 1385 3.2774 80.18 s 84.0 ms <- crosses 3.28 ONLY here, margin 0.0026 + read: CONVERGENCE-BOUND AT THE TAIL. The loss is still 3.331 at step 1250 (0.051 + ABOVE target) and only crosses 3.28 in the final 135 steps — and those steps + are the EXPENSIVE ones (~84ms vs ~32ms early), because batch+seq ramp across + the 3 stages. The final 135 steps cost 11.4s (14% of wall) and earn 0.054 of + loss at a razor 0.0026 margin. Naive step cuts are impossible. + lever: two real openings — (a) make the curve reach 3.28 EARLIER (convergence) so the + expensive tail steps can be cut; (b) shave per-step. (a) is the big lever. + decision: this is the floor to beat; it already certifies at N=3, no work needed on it. + → next: profile ONE Stage-3 step to see the per-step split, then commit to a lever. +``` + +### OP 1 — profile one expensive step, pick the lever by the numbers + +```bash +# nsys/ncu/nvprof are NOT installed on the H100 image — torch.profiler only. +# wrap steps 1250-1255 (Stage 3, the expensive regime) via the existing env hooks: +ssh "$NANOGPT_REMOTE" "cd '$NANOGPT_BENCH_ROOT' && \ + NANOGPT_PROFILE_START=1250 NANOGPT_PROFILE_END=1255 \ + DATA_PATH='$NANOGPT_DATA_ROOT' OMP_NUM_THREADS=8 \ + '$NANOGPT_PYTHON' -m torch.distributed.run --standalone --nproc_per_node=8 train.py" +``` + +```text +PROFILE — one Stage-3 step (~82 ms), real per-step split (research/PROFILE.md): + GEMM (aten::mm) 32.3 ms total / 24.2 self <- MLP + projections dominate + ReLU²-MLP Triton kernels 20.9 ms self + FA3 backward 9.6 ms ; FA3 forward 2.0 ms + optimizer step 5.6 ms total / 4.6 self + NCCL all-gather + r-scatter 2.2 + 1.7 = 3.9 ms <- comms is NOT the wall + "Command Buffer Full" 14.0 ms (604 launches / 5 steps) <- launch overhead + read: per-step is GEMM/MLP + FA3 + ~14ms launch bound; comms is small. But this recipe + is #83 — per-step is already near-roofline. Per-step shaving is the 1-2% game. + decision: ATTACK CONVERGENCE FIRST (cut tail steps), per-step SECOND. This is the exact + fork the live run got wrong (it went straight to FP8/MLP per-step precision). +``` + +### OP 2 — the BIG lever: convergence (named knobs, one change each, read the CURVE) + +Each experiment is a single-variable edit to `solution/train.py`, scored `./eval_solution.sh +solution 3`, and judged on **whether the curve crosses 3.28 earlier at step 1250**, not just +on the final number. The real knobs (line-cited): + +```text +a) NorMuon regularization — lr=0.023 (train.py:1858), weight_decay=1.2 (:1861), + beta2=0.9 (:1860), momentum schedule warmup 300 / 0.85→0.95 (:1780). + Try lr {0.021,0.025}, wd {1.0,1.5}: does val_loss@1250 drop below 3.331? +b) *** ADD annealed SGLD/Langevin noise to the NorMuon update *** — the seed has NO noise + hook (grep confirmed none). Injected, annealed gradient noise is one of Recursive's five + inventions and the single highest-value convergence bet here: it regularizes → reaches + the target in fewer steps. This is a NEW mechanism in the optimizer, not a knob twist. +c) Schedule — 3-stage lr_mul 1.0/1.52/1.73 (:1765-1770), cooldown_frac=0.60 (:1777, anneal + to 0.15·LR). Try pulling the cooldown earlier or lifting Stage-3 lr: earn the same tail + quality in fewer expensive (84ms) steps. +d) The cut — IF any of the above makes val_loss<=3.28 by ~step 1300, then drop + num_scheduled_iterations 1375->~1290 (:1680) and re-measure. ~85 tail steps × 84ms ≈ 7s. + + CAND normuon_sgld_noise — (b), on the seed floor + command: edit train.py NorMuon update; ./eval_solution.sh solution 3 + measured: + read: WIN iff the curve crosses 3.28 EARLIER (val_loss@1250 < 3.331) at equal/less time + lever: convergence (fewer steps) — the big lever + decision: keep if it moves the crossing earlier; then STACK (c)+(d) onto it, co-tuned + → next: stack winners; the moment mean<<3.28 at N=3, certify +``` + +> The live run never edited any of (a)–(d). It produced its speedups entirely on the +> per-step/precision side, which is why it landed at 79.77s and not below — the big lever +> went unworked. The first thing my run does differently is spend its first missions here. + +### OP 3 — the statistical discipline (how the win actually banks) + +```text +CAND — mean clearly inside the target at N=3 + command: ./eval_solution.sh solution 3 -> ./eval_solution.sh solution 10 + rule: the moment N=3 shows mean val_loss CLEARLY < 3.28 with small sd, CERTIFY at + N=10 and BANK as the new floor. Do NOT keep engineering validity you have. + evidence: this is exactly what won tonight: hybrid post-only MLP read INVALID at N=3 + (val_loss 3.2765, p=0.01313) — a POWER miss, not a quality miss — and the + SAME recipe certified VALID at N=10 (val_loss 3.2776±0.0022, t=−3.389, + p=0.004007, 79.77s±0.06) with ZERO recipe change. + stack: keep a current-best recipe; ADD each winning mechanism onto it and co-tune; + revert only a knob that measurably hurts. Never revert to the bare floor. +``` + +### OP 4 — only now the small lever: per-step (co-tuned onto the best stack) + +```text +- leaner / fused ReLU²-MLP activation storage — the live run's one real win + (mlp_post_only 79.55s val_loss 3.2771; this is ≈ one of Recursive's inventions). KEEP it. +- cut the ~14ms "Command Buffer Full" launch overhead: fuse the many small kernels / use + CUDA graphs for the resident step. +- FP8 — only with DELAYED/CACHED scaling. The live run proved naive FP8 here is net-negative: + fixed-scale diverged (val_loss 7.69), dynamic per-step amax was SLOWER (81.29s) because the + amax reductions ate the GEMM win. Low priority, structural; fix scaling-fusion or skip. +``` + +## The nails — what the live run actually did (do NOT repeat) + +The procedure above is the known-good path. The agent's real run hit these; the expensive +failures on a speedrun are **process and statistics**, not the recipe. + +- **Nail 1 — the perpetual-prototyper loop.** ~6 missions over ~3 hours, each `{take floor → + build one variation → N=3 → miss by a hair → revert to floor → done}`, floor stuck at + ~80.16s while a quality-valid 79.7s near-win sat un-certified. A "successful" mission that + neither moves the floor nor certifies a near-win is churn dressed as progress. +- **Nail 2 — reading a POWER miss as a QUALITY miss.** `p=0.085` with `val_loss=3.2771` + (clearly < 3.28) was treated as "engineer the recipe harder." It was underpowered, not + low-quality. The fix for a power miss is more seeds (N=10), not another mechanism. +- **Nail 3 — wrong lever for hours.** All real work went to per-step FP8/MLP precision (the + small, roofline-bounded lever) while the optimizer/schedule/noise (the big, compounding + lever, §OP 2) went untouched — so the run stayed ~2.5s short of 77.3s. +- **Nail 4 — testing in isolation and reverting to the bare floor.** Each mechanism was + measured against the seed and reverted, so nothing compounded. Recursive's 77.3s is FIVE + stacked inventions; the right unit of work is a current-best STACK. +- **Nail 5 — infra/operational.** A daemon self-restart once lost the persisted Manager + classification; a restart landed mid-N=10-recert and marked that mission `failed` + even though the orphaned scorer finished valid — the win computed but did not bank cleanly. + Restart only at clean mission boundaries; verify env + `import` first. + +## How to apply this chain to another speedrun +1. OP 0: score the seed (`./eval_solution.sh solution 3`) with `set -o pipefail`, and extract + the real convergence curve. Never fabricate `train_time`/`val_loss`/`p`. +2. OP 1: profile one expensive step; read whether per-step is compute/MLP/comms/launch bound, + and whether per-step is already near-roofline (a near-SOTA seed usually is). +3. Pick the lever by leverage: **convergence (fewer steps) first**, per-step second. Name the + exact knobs from the recipe. +4. For each candidate, record the full chain block with real scorer numbers; on every INVALID + classify QUALITY vs POWER. +5. The moment a mean is clearly inside the target, **N=10-certify and bank**; **stack, don't + revert**. +6. Stop a line when the gap to the next anchor needs an invention you don't have, and say so. + +## Response shape +- State the exact scorer command and whether it exited 0; the seed's measured baseline and curve. +- Show the decomposition (per-step by stage, where the curve crosses) and which lever you chose, why. +- For each candidate, the full chain block with real `train_time/val_loss/p`; each INVALID + labeled QUALITY or POWER. +- Quote the frozen `SCORE` line for every banked (N=10) candidate. +- Frame the result honestly against the same-harness baseline and named anchors, like-for-like. diff --git a/packs/speedrun/skills/engineer/speedrun-sota-optimization.md b/packs/speedrun/skills/engineer/speedrun-sota-optimization.md new file mode 100644 index 0000000..26d4d8e --- /dev/null +++ b/packs/speedrun/skills/engineer/speedrun-sota-optimization.md @@ -0,0 +1,388 @@ +--- +name: "Speedrun SOTA Optimization" +description: "Senior-researcher methodology for training-speedrun benchmarks (modded-nanogpt / NanoGPT-speedrun and kin): minimize wall-clock to a fixed quality target under a statistical validity rule. Covers research-first retrieval of prior art before building, the bottleneck taxonomy (convergence / step-cost / comms / precision-stability), the N=3 iterate and N=10 certify discipline, and a toolkit ordered by leverage — optimizer and schedule first, kernels and precision last. Expertise to learn, not a recipe to copy." +--- + +## Title +Speedrun SOTA Optimization + +## What this is +This is **distilled human expertise** — how a senior ML-systems researcher actually +thinks about a training-speedrun, not a script to follow. Read it to acquire the mental model +and the priors; do not treat it as steps to mechanically execute or a recipe to +transplant. The numbers and worked references exist to teach the *method*; the method +generalizes across speedrun tiers and metrics. When a real run teaches you something +sharper, evolve this. (Companion: [Speedrun Hands-on Trace](speedrun-hands-on-trace.md) is one fully-worked, +failure-first example of the loop.) + +## When to use +- The objective is to **minimize wall-clock training time** to reach a **fixed quality + target** (e.g. `val_loss <= 3.28`, `val_bpb <= X`) on real GPUs (8xH100 / B200), with a + frozen scorer and a **statistical validity rule** (a one-sided t-test over N runs). +- The task names an editable recipe (`train.py` + kernels), a frozen scorer, and a numeric + wall-clock metric — modded-nanogpt / nanochat-style speedruns and their kin. + +## When NOT to use +- A single GPU kernel (use the task's single-kernel procedure), a paper benchmark matrix, or an + RL/post-training run. +- The scorer is missing and cannot be reconstructed — report what is missing first; + do not invent a metric or a `p`-value. + +--- + +## 0. Research-first: you are knowledge-limited — RETRIEVE before you build + +This is the section the agent most needs and most skips. A senior researcher's first move +is **not** to think harder; it is to **go read what humans already figured out**. An LLM +agent has a sharper reason to: your knowledge is *parametric* — frozen at cutoff, capacity- +bounded, weakest exactly on the long-tail/post-cutoff facts that matter here (new optimizers, +new kernels, the SOTA recipe's rationale, hardware-specific tricks), and you are trained to +sound confident, so from memory you will emit plausible-but-wrong technique facts ("X gives +2×"). The evidence is blunt: on the **Automated LLM Speedrunning Benchmark** (these very +NanoGPT records) frontier agents largely *cannot re-implement even the next record's gains* +when handed the prior record's code plus pseudocode hints; **FIRE-Bench** finds frontier +research agents stay under ~50 F1, failing at **experimental design + evidence-grounding**, +not at writing the kernel. The binding skill is **retrieve → reproduce → verify**, not raw +cleverness. + +**Invention is recombination, so retrieve and stack — do not try to invent from scratch.** +Bibliometrics across tens of millions of papers (Nature 2022, *atypical combinations*) show +genuinely unprecedented ideas are rare; almost all progress is *novel re-mixing of known, +proven parts*. Every speedrun record is the prior record's code **plus a few small, +orthogonal, already-published gains** stacked on top. So your job is NOT a never-seen +optimizer; it is to aggressively retrieve the menu of known levers, stack the orthogonal +ones, re-implement each carefully (the step agents fail), and measure. Reciting a known +trick from memory and calling it "my invention" is the classic agent failure that +literature-grounded novelty checkers exist to catch — and pulling a technique from memory +instead of from its concrete source is how you get the coefficients/conditions wrong. + +**The discipline (search-then-build — the order real end-to-end research systems use):** +1. **Reproduce first.** Stand up the baseline AND the named anchor on *your* hardware and + re-measure like-for-like before trying to beat anything. Reproduction is research, not setup. +2. **Chase the most concrete source.** pseudocode/repo/commit-diff/reference-kernel/ablation- + table > prose > abstract. Reasoning about a technique in the abstract is where agents flail; + go get its executable form and read it. +3. **Corroborate, don't trust one blog.** A single "N× speedup" is a parametric-quality claim + until a second source confirms it; treat headline multipliers as **upper bounds under + unequal tuning** (*Fantastic Pretraining Optimizers*, 2509.02046: matrix optimizers are only + ~1.1–1.4× and shrink toward ~1.1× at ~1.2B — and tune the BASELINE as hard as the new thing). +4. **One lever, measured against retrain variance, then stack.** Adopt a change only if it + clears run-to-run variance (§3); then add the next orthogonal lever onto the best stack. + +**The anti-cheat line (non-negotiable):** retrieve GENERAL technique, methodology, and design +*rationale*. NEVER retrieve this task's leaderboard answer / best-solution code. Understanding +*why* a component exists is research; copying the answer key is disqualifying. + +**The menu of human knowledge to retrieve (named, so you can search for it):** + +| Lever | Technique (search the arxiv/repo, don't recite) | Axis | +|---|---|---| +| optimizer / fewer steps | **Muon** (orthogonalized momentum, matmul-only Newton-Schulz) + **Moonlight** (RMS-match to AdamW + decoupled WD to scale it); **SOAP** (Adam in Shampoo eigenbasis, eigendecomp every k); **Sophia** (diagonal-Hessian + clipping) | convergence | +| LR / horizon | **WSD** (warmup-stable-decay: long plateau, short cooldown — cash out a converged ckpt at any budget); **muP/muTransfer** (tune LR on a small proxy, transfer zero-shot — a meta-speedup for your tuning budget) | convergence + tuning cost | +| batch | **critical batch size** + **batch-size warmup** (below CBS bigger batch ≈ linear step savings; above it wastes tokens) | steps ↔ per-step | +| regularization | annealed **Langevin/SGLD** gradient noise (generalization-per-step) | convergence | +| data | **RHO-Loss** (online reducible-holdout batch selection — skip already-learned/noise), **DoReMi** (proxy-tuned data mixture), **sequence-length warmup** (cuts early attention FLOPs AND stabilizes) | convergence, ~free | +| per-step cost | **FA3**/fused kernels; **torch.compile** fusion + **CUDA graphs** (launch-bound); **FP8 GEMMs** with delayed scaling (watch SwiGLU outlier loss spikes) | per-step | +| variance / the metric | **LAWA / weight-averaging / EMA** denoise the iterate → lower run-to-run variance → certify with the mean riding closer to the target = fewer steps. (Classic **SVRG is ineffective** in DL; momentum + larger batch + averaging are the variance reduction that works.) | the t-test lever | + +**Search playbook (general technique only — never the answer key):** the arxiv/repo for each +lever above; *Fantastic Pretraining Optimizers* before believing any optimizer multiplier; the +diagnostic method (roofline, MFU ≈ achieved/peak with ~6N FLOPs/token, nsys-then-ncu, +torch.profiler op attribution) so you self-measure the bottleneck; and a literature-grounded +novelty check before you ever call something "new". + +--- + +## 1. The mental model: wall-clock is steps × per-step-cost + +A speedrun's wall-clock is, to first order: + +```text +train_time ≈ counted_steps × per_step_cost (+ fixed costs: compile, warmup) +``` + +There are exactly **two levers**, and they are not equal: + +- **Fewer steps to the target** — a *convergence* improvement: the loss curve reaches the + target in fewer optimizer steps. Lives in the optimizer, the LR/schedule, init, data + order, batch/seq sizing, architecture. **This is the 10x lever and it compounds**: a + recipe that needs 1200 steps instead of 1385 is 13% faster *and* every per-step saving + multiplies against fewer steps. +- **Cheaper per step** — a *throughput* improvement: each step costs less (faster attention, + leaner MLP, FP8 GEMMs, comms overlap, fused kernels). Bounded by the **hardware roofline**: + once a step is near peak, there is little left, and precision tricks carry structural + overhead. + +A training run, like a kernel, **is bottlenecked by one of these and wastes effort spent on +the other.** The whole craft is: find which one binds, attack it, re-measure. + +> The single most common senior-level error on a speedrun is spending the day on per-step +> kernel/precision micro-opts (fun, visible, roofline-bounded) while the **convergence** +> lever — which is where the leaderboards are actually won — goes untouched. Recursive's +> 77.3s frontier on Task 2 was **five stacked inventions**, most of them convergence/optimizer +> changes (annealed SGLD noise in NorMuon, sign-agreement Adam on the bigram/value banks, +> schedule retunes), with only one leaner-MLP kernel. Lever (a) first. + +--- + +## 2. Honesty rules (non-negotiable, the only hard floor) + +- The **frozen scorer** is the only source of truth for `train_time`, `val_loss`, and + validity. A self-timed number is a hypothesis, not a result. +- **The score is the VERIFIER's re-measured `train_time`, mean over N runs, for a VALID + candidate only.** A faster run that fails the t-test is **INVALID, not a win** — never + bank it, never report it as the result. +- **No fabricated numbers.** `p(mean=10).** N=3 is a probe, not a + conclusion. +- **Classify every INVALID: QUALITY miss vs POWER miss.** + - *Quality miss*: `mean > target` (or barely under with large sd). The recipe genuinely + isn't good enough — engineer convergence/quality. + - *Power miss*: `mean << target` with small sd, but `p` just over α (e.g. mean 3.2765 vs + target 3.28, p=0.013 at N=3). **The recipe is already good; only N is too small.** `p` + shrinks with N at fixed mean/sd, so a mean clearly inside almost always certifies at N=10. +- **The cardinal sin:** treating a power miss as a quality miss and re-engineering a recipe + you have already won. The fix for a power miss is **more seeds**, full stop. +- **Bank the floor the moment you have a clearly-valid faster candidate** — N=10-certify and + move the global best to it. Do not keep "improving" validity you already hold. +- **Stack, don't revert.** Maintain a *current-best recipe*; add each promising mechanism + onto it and co-tune. Revert only a mechanism that *measurably* hurts. A run that reverts to + the bare floor after every experiment can never reach a stacked frontier. + +> Worked failure ([Speedrun Hands-on Trace](speedrun-hands-on-trace.md)): a 79.55s candidate with `val_loss=3.2771` +> (clearly < 3.28) read INVALID at `p=0.085` (N=3). It was a *power* miss. The run spent ~6 +> missions / 3 hours building further mechanisms; the same hybrid recipe certified VALID at +> N=10 (`p=0.004`, 79.77s) with **zero recipe change**. The win was in hand for hours. + +--- + +## 4. Diagnosis: where does the wall-clock go? + +Optimizing the non-bottleneck is the #1 way to waste a day. Decompose first, with real +measurement. Use direct GPU access only when the mission manifest provides a +working remote command; otherwise record the infrastructure failure. + +- **Step decomposition:** `per_step = train_time / steps`. Know it before touching kernels. +- **The convergence curve (the most important plot):** `val_loss` vs step. *Where* does it + cross the target? If it crosses only in the final few % (e.g. val_loss@step1250 ≈ 3.331 for + a 1385-step run targeting 3.28), **naive step cuts are off the table** — the end of the + curve has no slack, and you must improve convergence to cut steps. If it crosses early with + a long flat tail, the tail is wasted steps — cut or anneal them. +- **Per-step profile:** decompose a steady-state step (after compilation) into forward / + backward / optimizer update / **NCCL comms (reduce/gather)** / data load. Use + `torch.profiler` or CUDA events; on 8x, NCCL all-reduce and the optimizer's matrix work + (Muon/NorMuon `XTX`/`XXT`/polar) are frequent hidden costs. Attribute the per-step cost to + **one** dominant term before optimizing it. +- **The reference ceilings (carry them always):** + - run `torch.compile` / the seed as-is to know the *absolute* step-cost floor on this box; + - measure NCCL bandwidth and FA3 cost so you know what is comms vs compute; + - know the *named anchors* (seed, public record, automated frontier) in **your** harness + units, re-measured — not their published numbers. +- Attribute the gap to **one** cause (convergence vs a named per-step term) before choosing a + move. "It's steps *or* per-step" is a measurement you skipped. + +--- + +## 5. The bottleneck taxonomy (which wall?) + +| Wall | What binds | Tell (from the decomposition) | First move | +|---|---|---|---| +| **Convergence-bound** | needs too many steps to hit target | curve crosses target only at the very end; long tail at high loss | optimizer (noise/regularization), schedule, init, data order — the big lever | +| **Step-cost: compute-bound** | forward/backward FLOPs dominate per step | per-step ~flat in batch; GEMM/attention is the hot term | FA3/attention impl, leaner MLP, tensor-core precision, fused kernels | +| **Step-cost: comms-bound** | NCCL reduce/gather on 8x | per-step rises with world size; reduce/gather a large slice of the step | overlap comms with compute, bucket/all-reduce tuning, lower-precision grads | +| **Step-cost: optimizer-bound** | Muon/NorMuon matrix work per step | optimizer update is a large per-step slice | fuse/precision the optimizer kernels; cheaper polar/orthogonalization | +| **Precision-stability-bound** | low precision diverges or needs costly scaling | FP8/FP6 runs blow up or need per-step amax that eats the win | delayed/cached/per-block scaling, partial coverage, or back off precision | +| **Fixed-overhead-bound** | compile/warmup is a big fraction | short runs; wall >> steps×per-step | amortize compile, fewer recompiles, CUDA graphs | + +The one people miss on a speedrun: **convergence-bound looks like "the recipe is just slow"** +— but the lever is the optimizer/schedule, not the kernels. If the curve needs 1385 steps and +you only ever shave per-step cost, you are polishing the small lever forever. + +--- + +## 6. The optimization toolkit, ordered by LEVERAGE + +Apply in this order. The biggest wins are at the top; the per-step micro-opts at the bottom +are where the night gets burned if you start there. **Ask "what is the minimum number of +steps × the minimum per-step cost this target requires?" before "how do I make this kernel +faster?"** + +1. **Reduce steps-to-target — convergence (10x lever, compounds).** + The optimizer and its regularization (Muon/NorMuon; injected noise — annealed SGLD/Langevin; + sign-agreement / sign-trick updates on specific banks); the LR/warmup/cooldown schedule and + its retunes; init; batch/sequence sizing; data ordering/curriculum; architecture levers that + aid optimization (softcap, embedding splits, residual scaling). Most leaderboard deltas live + here. Measure on the **convergence curve**, and always re-check the target is still hit. +2. **Reduce per-step cost without hurting convergence.** + Better attention impl (FA3); a leaner forward (the post-only / fused ReLU² MLP that stores + fewer activations); kernel fusion to cut HBM round-trips and launches; **comms overlap** + (start NCCL on ready grads while compute continues). These are real but bounded by roofline. +3. **Precision as a lever (within stability — a dial inside a hard constraint, not free).** + FP8/FP6 GEMMs on projections — but a per-step/per-block **scale is structural overhead**, so + FP8 is net-positive only when the scaling is **delayed/cached/fused** and the op is the + bottleneck. Naive fixed-scale diverges; dynamic per-step amax often costs more than the GEMM + saves. Expect to *fight* for net-speedup; fix layout/scaling first, and report net-slower as + net-slower. (See [Speedrun Hands-on Trace](speedrun-hands-on-trace.md), nail 3.) +4. **Schedule / step-count tuning — LAST, and only after convergence is improved.** + Cutting or annealing steps is valid only if the curve has tail slack or a convergence win + created it; a naive step cut on a tight curve just fails the t-test. Verify on the curve, not + by hoping. + +**The leverage rule, stated once:** a convergence win multiplies against every per-step win; +a per-step win is capped by the roofline. When unsure which to do next, do the convergence +experiment. + +--- + +## 7. Optimizer / architecture prior library (the priors) + +Internalize these so the curve *confirms* rather than *discovers*: + +- **The tier sets the regime.** GPT-2-small-class modded-nanogpt to a fixed val_loss on 8xH100 + is **convergence-bound near the end**: the seed already uses FA3 + a strong optimizer + (Muon/NorMuon) + FP8 GEMMs + fused Triton + a multi-stage schedule + ~1385 steps, and the loss + crosses target only in the last ~10%. So per-step cost is already near-roofline; the open lever + is *fewer steps via better optimization*, not cheaper steps. +- **Muon / NorMuon** orthogonalize the update (polar/Newton-Schulz `XTX`/`XXT`); they are strong + but their matrix work is a per-step cost and their **regularization is tunable** (injected + noise, momentum, the orthogonalization budget). Convergence gains and step-cost both live here. +- **Injected-noise regularization (SGLD/Langevin, annealed)** can improve generalization-per-step + → fewer steps to target. A known frontier move; cheap to try, measured on the curve. +- **Sign-agreement / sign-trick updates** on specific parameter banks (bigram/value/embedding) + are a known lever for these recipes (#83 itself is "Sign Trick on Bigram Embed"). +- **FP8 on 8xH100 (Hopper, E4M3/E5M2)** needs scaling; delayed/per-tensor scaling amortizes the + amax. The attention projections and MLP GEMMs are the candidates; the MLP activation-storage + path is where a leaner-kernel win lives. Treat as the small, structural lever. +- **NCCL on 8x** — reduce/gather can be a large step fraction; overlap with compute and consider + lower-precision gradient comms within the stability budget. + +A senior researcher reads "GPT-2-small to val_loss 3.28, seed already FA3+NorMuon+FP8, curve +crosses 3.28 only at step ~1350/1385" and *already knows*: this is **convergence-bound at the +tail**, the leaderboard delta is an optimizer/noise/schedule change that pulls the crossing +earlier, and the per-step kernels are a secondary 1–2% game. The decomposition then *quantifies* +the gap; it does not reveal the regime. + +--- + +## 8. Operator / lever → canonical move + +| Symptom (from §4) | Binding lever | Canonical winning move | +|---|---|---| +| curve crosses target only at the end; need fewer steps | convergence | optimizer noise/regularization, schedule retune, init, data order — re-measure the curve | +| optimizer update is a big per-step slice | optimizer step-cost | fuse/precision the polar/orthogonalization kernels | +| NCCL reduce/gather large on 8x | comms | overlap comms with compute; lower-precision grads within tolerance | +| MLP/attention GEMM is the hot per-step term | compute | FA3, leaner fused MLP, tensor-core precision with scaling | +| FP8 candidate diverges or is net-slower | precision-stability | delayed/cached/per-block scale, partial coverage, or back off | +| a faster candidate, mean clearly < target, p just over | **statistical power** | **N=10 certify and BANK — not another mechanism** | +| many mechanisms tried, floor not moving | process | stop nibbling; stack onto best, bank the near-win, work the big lever | + +--- + +## 9. The experimental discipline + the measured causal chain + +Run the search like an experimentalist: + +- **One variable per experiment.** Attribute the gap to one cause (convergence vs a named + per-step term) before the next move. +- **Always carry the reference ceilings** (seed, public record, automated frontier — all + re-measured on your harness) so you know absolute distance to the limit, not just relative + deltas. +- **Classify every miss (quality vs power) and bank every clearly-valid near-win at N=10** + before doing more mechanism work (§3). +- **Stack, don't revert** (§3, §6). +- **Know the irreducible floor and stop there.** A recipe at the roofline on per-step with a + tight convergence curve, a gap to the next anchor that needs an invention you don't have — + recognize when the remaining gap is the frontier, not your code, and say so honestly instead + of grinding noise or re-certifying validity you already hold. +- **Correctness/validity (the frozen t-test) → decomposition → one mechanism → re-measure → + attribute.** + +Record each candidate as the **measured causal chain** (see [Speedrun Hands-on Trace](speedrun-hands-on-trace.md) for a +filled example): + +```text +CAND + measured: train_time (scorer, N), val_loss (scorer), p(mean VALID/INVALID + decompose: steps × per_step; convergence: val_loss@mid-step + read: faster/slower? quality in or out? if INVALID -> QUALITY or POWER miss? + attribution: which lever moved (convergence / per-step term / precision-stability), from the numbers + decision: bank N=10 / stack & co-tune / revert / abandon — by the rule + → next: the next mechanism, chosen by the binding constraint +``` + +Lightweight persisted files (for the multi-round harness, not the research itself): +`research/GROUND_TRUTH.md` (scorer command, hardware, target, t-test rule, decomposition, +re-measured anchors), `research/PROFILE.md` (per-step breakdown + convergence curve), +`experiments//RESULT.md` (the chain block + raw `SCORE` log), +`RESULTS.md` (final table ranked by `train_time` among VALID candidates, honest about the +power-vs-quality status of every near-miss). + +--- + +## 10. Worked example (compact) + +NanoGPT-speedrun (Task 2) on 8xH100, target `val_loss <= 3.28`, frozen +`./eval_solution.sh solution `, validity `p(mean<3.28) < 0.01`. Seed #83 re-measured: +`80.18s, val_loss 3.2774, p=0.00341` (N=3); `per_step ≈ 57.9ms × 1385`; `val_loss@1250 ≈ 3.331` +(convergence-bound at the tail). + +```text +CAND mlp_post_only_hybrid — leaner ReLU² MLP storage, exact path on sensitive layers + measured: 79.73s, val_loss=3.2765, p(mean<3.28)=0.01313 (N=3) -> INVALID + decompose: per-step win vs seed; convergence held; curve still crosses ~3.28 at the tail + read: mean 3.2765 CLEARLY inside 3.28, p just over 0.01 -> a POWER miss, not quality + attribution: real per-step structural win (leaner MLP ≈ 1 of Recursive's inventions) + decision: N=10 certify NOW (mean this far inside almost always passes at N=10) + re-measured: 79.77s ± 0.06, val_loss=3.2776 ± 0.0022, t=−3.389, p=0.004007 (N=10) -> VALID + → next: below ~79.5 needs the BIG lever — optimizer noise / schedule for step reduction, + or stacking more inventions; single-mechanism-then-revert is spent +``` + +This is `N=10 certification` (§3, the statistical discipline) chosen because the miss was a +*power* miss — not "build another mechanism" (the trap) and not "tune the schedule" (premature). +A fuller failure-first version is in [Speedrun Hands-on Trace](speedrun-hands-on-trace.md); derive your own from your numbers. + +--- + +## 11. Senior-level mistakes (sharper than "common pitfalls") + +- Chasing per-step kernel/precision micro-opts (small, roofline-bounded lever) before the + optimizer/schedule (the big, compounding lever). +- Reading a **power** miss (mean clearly inside, p just over at N=3) as a **quality** miss and + re-engineering a recipe you have already won. +- Not banking a clearly-valid faster candidate immediately at N=10 — leaving the record un-cashed. +- Testing each mechanism in isolation and **reverting to the bare floor**, so improvements never + stack toward a frontier built from stacked inventions. +- Naive step-count cuts on a convergence curve with no tail slack (fails the t-test). +- FP8/low-precision without fused/cached scaling → net-slower or divergent, reported as "tried FP8". +- Declaring a win from a self-timed, N=1, or warm-state number instead of the frozen t-test. +- Restarting/interrupting **mid-certification** and losing a banked score; or comparing your number + to a published anchor measured on different hardware without saying so. +- Grinding noise near the frontier (or re-certifying validity you already hold) instead of working + the big lever or stopping honestly. + +## Response shape +- Target metric, scorer command, hardware, the seed's re-measured baseline, and the named anchors + in your harness units. +- The decomposition (per-step, convergence curve) and the bottleneck wall, with the evidence for it. +- The measured causal chain per candidate (frozen scorer numbers only), each INVALID labeled + QUALITY or POWER. +- Absolute distance to the next anchor / frontier, and whether closing it needs the big lever or a + real invention you don't yet have. +- The next mechanism chosen by the binding constraint, with the exact scorer command to run.