Skip to content

[model] Add an add_model skill documenting the model-port workflow - #5636

Open
shuhuayu wants to merge 1 commit into
pytorch:mainfrom
shuhuayu:add_model
Open

shuhuayu wants to merge 1 commit into
pytorch:mainfrom
shuhuayu:add_model

Conversation

@shuhuayu

@shuhuayu shuhuayu commented Oct 27, 2026 •

Copy link
Copy Markdown
Contributor

human notes:

  1. this is a skill used to draft a new model support in torchtitan so one can iterate with agents with the draft,
  2. covering model definition, parallelisms, numerical parity, feature and e2e tests,
  3. following 1) titan coding styles in naming, comments, file structure, 2) proper reusing existing modules, abstract boundaries.

Why

The add_model guidance predates current TorchTitan APIs and needs a concrete validation plan for new model ports. A numerical golden is useful only after the debug recipe is proven repeatable.

Recent model-port reviews found parameter/optimizer decisions, saved training memory, and redundant abstractions late. These checkpoints require evidence that the design, memory, and test plans were checked before proceeding.

Changes

  • Document current flavor/build, recipe, lifecycle, sharding, checkpoint, and shared component APIs.
  • Search shared components, other model packages, and relevant upstream libraries at the function level. Extract only reusable primitives into shared code and update existing callers. Record candidate functions/locations, the chosen implementation or backend, and reasons for new code before implementation.
  • For eager/reference attention, use attn-gym's matching reference implementation when available and compatible. Check layouts, masks, scaling, auxiliary outputs, and backward support; document any missing capability or semantic difference before implementing new attention math.
  • Require design review before implementation: component reuse, logical parameter shapes/storage, optimizer policy, ownership, prerequisites, and a test plan.
  • Require a training memory estimate covering saved backward tensors, transient unsharded weights, gradients, optimizer state, and workspaces. Inspect reduced backward storage before large reference/GPU checks and measure a short baseline training run before long training or claiming feasibility.
  • Require a simplification pass before expensive validation. Justify new wrappers, overrides, files, and shared APIs; preserve inherited compile/remat contracts. Each proposed test names its uncovered invariant, existing coverage, and independent expected result.
  • Require component/full-model forward and backward reference checks, offline parallelism comparisons with correct gradient scaling, and compact numerical evidence.
  • Check distributed lifecycle: gradients on ranks with empty work, trainability for disabled objectives, auxiliary-loss resets, packed boundaries, and logical values/optimizer moments after reload. Require HF compatibility and current native round trips; unsupported or ignored requested settings raise explicit errors.
  • Keep CPU feature tests, real combined FSDP/TP/EP/PP training, and strict debug goldens. Prove independent repeatability before golden export and replay.
  • Require PR stacks with prerequisite fixes where needed and an FSDP+EP MoE baseline (FSDP for dense models). Later parallelism order follows model dependencies. Each PR qualifies its own actual base/head, prerequisites, supported axes, and required checks, then repeats local review/revision until approved with no open must-fix findings. Keep optional performance work in follow-ups.

Example

Before implementing a port, inventory a large per-layer parameter and its optimizer assignment.
For sparse attention, inspect selection/loss functions even when the surrounding model class differs.
Use a compatible attn-gym reference backend for eager attention and record the relevant contracts.
Estimate saved inputs/weights through backward, gradients, optimizer state, and transient gathers.
A reduced check finds a concatenated weight retained; simplify the composition before long GPU jobs.
The initial model PR measures FSDP+EP memory and checks logical values/moments after save/load.
Later TP/PP/CP PRs qualify the prerequisites and numerical checks for the paths they add.
Each PR is revised and reviewed on its current base/head before the stable stack is submitted.

Validation

  • pre-commit run --all-files passed in an isolated checkout, including the new reference.

  • Checked skill metadata, 23 local links, and eight unchanged Bash/Python examples.

  • Repeatability command checks previously verified rejection of a one-ULP grad_norm difference; those examples are unchanged.

  • Reviewed amendment b93ac03e8 against prior head 14f47f03e: function-level reuse, compatible reference backends, and pre-implementation design evidence. The numerical parity workflow and executable examples are unchanged.

This changes documentation only; no model training or memory measurement was run for this PR.

@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Oct 27, 2026
@shuhuayu shuhuayu changed the title Add an add_model skill documenting the model-port workflow [model] Add an add_model skill documenting the model-port workflow Oct 27, 2026
@shuhuayu
shuhuayu force-pushed the add_model branch 3 times, most recently from 8cefe41 to ea77332 Compare October 29, 2026 22:39
@shuhuayu
shuhuayu marked this pull request as ready for review October 29, 2026 22:44

@tianyu-l tianyu-l left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re #5655
Do you think we can improve until @claude review accepts a one-shot effort from this skill? Or if the review skill is clearly wrong, we can change it, too.

@shuhuayu

Copy link
Copy Markdown
Contributor Author

Re #5655 Do you think we can improve until @claude review accepts a one-shot effort from this skill? Or if the review skill is clearly wrong, we can change it, too.

sure, let's do adversarial training on this

@tianyu-l

Copy link
Copy Markdown
Contributor

@claude review

@claude

claude Bot commented Nov 10, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @tianyu-l's task in 2m 16s —— View job


Request changes: review

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Verdict: Request changes -- An agent that follows this skill exactly will repeat most of the must-fix items from #5655's review. The skill tells it to commit golden provenance, add H100 tests and goldens where the repo uses A10G, and never warns it off single-consumer changes to models/common/. Its publishing step also conflicts with CLAUDE.md.

What this PR does. Adds a 1,097-line add_model skill: a phased workflow plus four reference files covering design and memory checkpoints, reference parity, test layers, goldens, and a local pr-review loop before submitting a PR stack. The API, path, and CLI claims are mostly accurate. Everything in the models/common table, the parallelize order, the loss_compare.py and run_tests flags, the ParallelismConfig fields and the EP mesh formula checks out.

Example. This is the one-shot test tianyu-l asked about. #5655 followed this skill, and here is where four of its must-fix items came from:

#5655 must-fix                                  <- skill text that asks for it
1. MAST/Manifold provenance in golden + README  <- SKILL.md:233 "commit ... golden and its provenance",
                                                   test_coverage.md:208 "run details ... beside the golden"
2. 3 single-consumer flags in models/common     <- SKILL.md:87,220 (no "start in model folder" rule)
6. four new H100 entries, pp2 subset of all     <- test_coverage.md:61-66,120 "add separate tests ..."
8. 374-line JSON report in tests/assets         <- numerical_parity.md:44 "Commit small test fixtures"

Fixing these lines is the cheapest way to get a port through @claude review in one shot.

Must fix

  1. test_coverage.md:236-252 -- The golden workflow (H100 suite, real_pg/h100/ only) doesn't match the repo, which keeps goldens in models.py on A10G/MI350X with both fake-PG and real-PG files. A models.py registration would fail in CI because the file is missing. "Every port needs a golden" also contradicts tests/README.md:106-113.

  2. test_coverage.md:61-66 -- Requires an 8xH100 combined test plus separate tests per uncovered feature; that should be one entry on the cheapest hardware, extended before adding more.

  3. SKILL.md:232-234 -- Tells the agent to commit provenance and fixtures. Provenance belongs in the PR description, and committed files must not contain internal-infra identifiers.

  4. SKILL.md:85-89 -- Missing the "model-specific variants stay in the model folder; no flags in models/common/ for one model" rule.

  5. SKILL.md:286-289 -- The agent publishes the stack and writes the descriptions itself. CLAUDE.md requires user approval of the exact content, and the description format belongs to the pr-description skill.

  6. SKILL.md:282-283 -- pr_review doesn't exist, and pr-review's branch mode can't take a base ref for stacked PRs.

  7. code_style_checklist.md:52-54 -- "must not default to None" is weaker than the rule (no default).

  8. Duplication, no single line. The same rules are repeated across files, which makes drift like item 7 likely:

    • the FSDP+EP / FSDP-for-dense baseline is stated in all five files;
    • the repeatability-before-golden gate is stated in four;
    • "record base/head" is stated in four;
    • Phase 1 restates torchtitan/models/README.md;
    • most of code_style_checklist.md paraphrases CLAUDE.md naming/style/config rules.

    State each rule once, in one file. Link CLAUDE.md, .claude/rules/, and models/README.md instead of restating them, and add only what they lack. My estimate is that this removes about a third of the text.

Should consider

  • SKILL.md:30-31 -- /pyrefly_ci_check doesn't exist.
  • test_coverage.md:105 -- "PP and checkpoint tests need use_real_pg=True" only matters under fake PG (tests/integration_tests/__init__.py:91-106). The h100 suite is real-PG only.
  • numerical_parity.md:39-42 -- Give the scripts' directory (scripts/checkpoint_conversion/). All five numerical_tests_*.py are tracked, so the "older or untracked" caveat doesn't apply. numerical_tests_example.py is the generic starting point.
  • numerical_parity.md:204 -- "Reuse adapter support for omitted tied output weights": there is no shared helper; each adapter implements it (e.g. llama3/state_dict_adapter.py:114-142).
  • test_coverage.md:118-120 -- The Kimi K3 examples are in b200.py. K3's golden is on the 2-GPU DistMuon FSDP+EP test, not the combined one, which contradicts "use the combined recipe for the golden" (line 199).

Questions

  • @tianyu-l: should pr-review's branch mode accept a base ref (/pr-review branch <base>) so stacked PRs can be reviewed against their parent? Fixing that on the review side looks right to me.
Details
  • Necessity: the problem is real. Ports currently re-learn the flavor/sharding/golden APIs, and #5655 shows both the value and the gaps. Docs-only, no core impact.
  • Current golden practice: there are no H100 goldens. Model goldens are in models.py/features.py, run on 8xA10G (.github/scripts/integration_test_real_pg.sh:40) and on MI350X, and are exported via the export_results dispatch input of .github/workflows/integration_test.yaml. Only kimi_k3_b200.txt lives outside that scheme.
  • Size: 1,097 lines, against pr-review (about 330 lines plus its checklist) and local_compile_perf (about 880 including references).

Not verified: none of the commands were executed (runner/loss_compare flags were checked by reading argparse).

Comment on lines +236 to +252
After the repeatability check passes and the test is registered in the `h100`
suite, export on the remote GPU node using its supported launcher and the
validated recipe. Replace the template names and paths. Use an empty output
directory for each run:

```bash
python3 -m tests.integration_tests.run_tests outputs/new-model-export \
--test_suite h100 --test_name new_model_fsdp+tp+ep+pp \
--execution_mode real_pg --gpu_arch_type cuda --gpu_arch h100 \
--ngpu 8 --no-parallel --export-numerics
```

Set the recipe's `training.steps` to at least 10 before export. The runner writes
the result to `outputs/new-model-export/real_pg/h100/` using the golden's filename.
Check every expected step, both metrics, run settings, and enabled features. Copy
the checked file into the registered `tests/assets/losses/real_pg/h100/` path.
Keep separate goldens for each GPU architecture and communication mode.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The golden workflow here doesn't match how the repo handles goldens:

  • No H100 goldens exist, and h100.py sets no golden_numerics_path.
  • Every model golden lives in models.py / features.py. Those suites run on 8xA10G (.github/scripts/integration_test_real_pg.sh:40) and on MI350X, with both fake-PG and real-PG files.
  • Goldens are exported through the export_results input of integration_test.yaml.

Following this text gives one of two bad outcomes. If the agent registers in h100.py as the template does, the golden lands on hardware no other golden uses, and it runs on the most expensive runner. If it registers in models.py (line 101 allows that), {gpu_arch} resolves to a10g/mi350x in CI. Only real_pg/h100/ was exported, so _read_golden_spec fails with file-not-found.

numerical_parity.md:157 ("Every model port needs a golden") also contradicts tests/README.md:106-113. That file says Qwen3.5 MoE and DeepSeek V4 deliberately ship without a golden because their A10G runs aren't bitwise-deterministic.

Fix: describe the current practice.

  • Add or extend one models.py entry at a topology that fits 8xA10G.
  • Add a golden only when that run is bitwise-repeatable, otherwise keep the entry as end-to-end coverage.
  • Regenerate both the fake-PG and real-PG files (tests.md "Golden Numerics").
  • Export through the CI dispatch.
  • Use h100.py only for paths A10G can't run (DeepEP, HybridEP, kernels that need sm90).

Comment on lines +61 to +66
Add the training test in the initial model PR with FSDP+EP for MoE models (FSDP
for dense models). Extend it as later PRs add TP+SP, PP, or CP. The completed
stack needs one test with FSDP, TP, EP, and PP together for an MoE model, normally
on a remote node with 8 H100s. For a dense model, cover FSDP/TP/PP and record EP as
not applicable. Use this run to catch interactions between parallelisms. Add
separate tests for features it cannot cover.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This requires every port to add an 8xH100 FSDP+TP+EP+PP test, plus "separate tests for features it cannot cover" and "another recipe if the combined test cannot cover a required feature or optimizer" (lines 66, 120). That pushes agents toward one new GPU entry per feature. It's how #5655 ended up with four new H100 entries, where pp2 was a subset of all_parallelism (its review, must-fix 6). None of the current h100.py model entries is a combined-parallelism test. The combined MoE tests run on A10G, e.g. qwen3_5_moe_fsdp+tp+ep and GPT-OSS FSDP4xTP2,EP4.

Fix: require one combined entry on the cheapest hardware that runs the debug model. Prefer an interleaved PP schedule with spmd_typechecking on. Fold features into that entry before adding another, and require a written reason for each extra entry (tests.md "Prefer Extending Existing Coverage").

Comment on lines +232 to +234
bitwise-identical full-precision loss and grad_norm at every step. Then export
and commit the small, architecture/mode-specific golden and its provenance,
register `golden_numerics_path`, and rerun without export. A deterministic

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Several lines tell the agent to commit provenance and reports with the golden:

  • here: "commit the ... golden and its provenance"
  • line 316
  • test_coverage.md:208-209: "Record other run details in comments or documentation beside the golden"
  • numerical_parity.md:44-45: "Commit small test fixtures"

Following those lines produced #5655's must-fix 1 and 8. The golden and the README contained MAST job IDs, torchx/metaconda images, and Manifold paths under a username, and a 374-line JSON report that no test reads was committed under tests/assets/.

Fix:

  • Committed goldens contain only what loss_compare.py and the runner write.
  • Run provenance and parity reports go in the PR description.
  • Commit a fixture only if a test reads it.
  • Committed files must not contain internal infrastructure identifiers (job IDs, internal storage paths, internal images, usernames).

Comment on lines +85 to +89
Use `torchtitan/models/common/config_utils.py` factories such as `make_gqa_config`,
`make_ffn_config`, `make_moe_config`, and `make_router_config` when they express the
architecture. Keep new concrete shared components in `torchtitan/models/common/`,
lifecycle contracts in `torchtitan/models/base/`, distributed helpers in
`torchtitan/distributed/`, and model-specific computation in its model package.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The skill says where shared code goes, and line 220 says to "extend shared flavor/config and adapter contracts". It never states the rule that keeps a port out of models/common/. CLAUDE.md principles 4-5 and models.md "Don't Over-Specialize" say that model-specific variants start in the model folder, and that shared modules don't get branches or flags for one consumer. torchtitan/models/README.md:12 says the same.

Without that rule, #5655 added three single-consumer booleans to common/embedding.py, common/norm.py and common/rope.py (its review, must-fix 2).

Fix: add one bullet here. "A variant of a shared component needed by one model is a subclass or local copy in the model folder. Don't add flags, branches, or hooks to models/common/ for it. Promote to common only when a second model needs it."

Comment on lines +286 to +289
PRs after earlier changes. Submit the stack targeting `upstream/main` only when
every PR passes; include dependencies, numerical evidence, and review results.
If a required skill, resource, or decision is missing, report the blocker and
keep stack submission pending.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Here and in code_style_checklist.md:120-123, the agent submits the stack itself and writes "scope, numerical evidence, and local review results in each description". That conflicts with CLAUDE.md PR Expectations #2: agents don't open or edit PRs unless the user approved the exact content, and they leave the "Summary (human-written)" placeholder. The pr-description skill, which owns the description format, is never mentioned.

"The repository's supported stack tooling" isn't named. upstream also isn't a remote in a standard checkout (this one has only origin).

Fix: "Prepare the stack locally. Write each description with the pr-description skill. Show the user the exact descriptions and publish only after they approve them."

Comment on lines +282 to +283
Resolve and read the `pr_review` skill (TorchTitan also names it `pr-review`).
Use its local branch mode with the PR's actual base and head refs. Review,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There is no pr_review skill. The only one is pr-review (.claude/skills/pr-review/SKILL.md:2), so the "also names it" hedge sends the agent looking for a skill that doesn't exist. The same applies to lines 29 and 322 and code_style_checklist.md:107,113.

Also, pr-review's branch mode is hardcoded to git diff main...HEAD, so "local branch mode with the PR's actual base and head refs" isn't something it supports. code_style_checklist.md:108-109 admits this and asks the agent to override it. For stacked PRs, the review would include every parent PR's changes.

Fix: use pr-review everywhere. Either add an optional base ref to pr-review's branch mode (/pr-review branch <base>), which tianyu-l said is fair game, or tell the agent to pass git diff <parent>...HEAD as the diff.

Comment on lines +52 to +54
- Use `ValueError` for bad config or input and `assert` for internal programmer
errors. Required config fields must not default to `None`. Put important
arguments first and prefer keyword-only options.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This restates CLAUDE.md and config.md more weakly than they do. The rule is that required fields have no default at all, not "not None". This is the risk of paraphrasing the rules instead of linking them; see the duplication point in the review body.

Suggested change
- Use `ValueError` for bad config or input and `assert` for internal programmer
errors. Required config fields must not default to `None`. Put important
arguments first and prefer keyword-only options.
- Use `ValueError` for bad config or input and `assert` for internal programmer
errors. Required config fields have no default. Put important
arguments first and prefer keyword-only options.

Comment on lines +30 to +31
- When available, use `/numerics_debugging` to localize unexplained drift and
`/pyrefly_ci_check` when local type checking disagrees with CI. Model-specific

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nothing in the repo is called /pyrefly_ci_check (it isn't under .claude/skills/ either). This is also referenced in code_style_checklist.md:94. Remove both references, or add the skill in its own PR.

Suggested change
- When available, use `/numerics_debugging` to localize unexplained drift and
`/pyrefly_ci_check` when local type checking disagrees with CI. Model-specific
- When available, use `/numerics_debugging` to localize unexplained drift.
Model-specific

@JavaZeroo

Copy link
Copy Markdown
Contributor

I used this skill at 96916c5 for the first version of Kimi K3.1 #6007. Two places caused most of my rework:

  1. Reuse across models. The reuse table only lists models/common/. K3.1 uses DSA like DeepSeek V4, but the agent compared the whole DSV4 classes (compressor, sink), decided they don't fit, and wrote its own top-k selection and indexer loss. Maybe add: also search other model packages for the same algorithm, and check reuse at the function level, not only the class level.

  2. Eager baseline. The task asked for an eager baseline, and the skill only names FlexAttention and varlen as backends to reuse. So the agent wrote its own attention math in a different layout and never looked at attn-gym. Maybe add: an eager or reference path should call attn-gym's own reference implementation.

Document a model port workflow that starts with a pinned reference and
unsharded numerical comparisons. Establish an FSDP+EP training baseline
for MoE models (FSDP for dense models), then extend distributed execution
before review.

Use current MODEL_FLAVORS/build_model_config APIs, the BaseModel lifecycle,
declarative sharding, and Python recipes. Reuse generic checkpoint
converters and bind model-specific state dict adapters on the model class.

Require tensor error checks with justified tolerances and backward
comparisons for new components. Validate MoE router scores, selections,
and weights independently of imposed-routing diagnostics.

Keep numerical methodology and code-style audits in linked references.
Require CPU tests of important features, combined real-GPU FSDP/TP/EP/PP
training, and a remote debug-recipe numerical golden with an independent
replay. Document histogram/state-update coverage for quantile balancing,
mesh sizing, golden export and CI registration.

Include exact loss and grad_norm comparisons for non-computation changes,
convergence evidence for new computation, and scale validation when
requested.

Make training-hook, input metadata, and cross-stage state contracts explicit.
Require independent remote debug-recipe repeatability checks before golden
generation, comparing every full-precision loss and grad_norm step. Include
scratch capture/comparison commands, then golden export and replay.

Require component and full-model forward/backward parity, offline comparisons
across parallelisms with gradient scaling checks, and a compact evidence table.
Stage model enablement with FSDP+EP for MoE models, additional parallelisms/kernels,
and optional performance work in a PR stack. Adapt the later parallelism order
to model dependencies, with TP+SP, PP, then CP as a suggested progression.
Require local pr_review/revision loops for every PR, including dependent
re-reviews, before submitting the reviewed stack.

Add evidence checkpoints from model-port reviews: review component reuse,
parameter storage, optimizer policy, and ownership before implementation.
Estimate training memory including saved backward tensors and transient weights;
inspect reduced components and measure the intended baseline before qualification.
Simplify wrappers and overrides before expensive validation, preserving compile
and lifecycle contracts. Justify tests by uncovered invariants and existing coverage.

Audit gradient participation, disabled objectives, auxiliary-loss resets, packed
boundaries, and checkpoint values/optimizer moments. Qualify each PR's prerequisites,
actual base/head, and supported axes independently. Use explicit config errors and
HF compatibility plus current native round trips without promising old native schemas.
@shuhuayu

Copy link
Copy Markdown
Contributor Author

I used this skill at [96916c5]

Thanks for trying it out and sharing feedback! You are absolutely right. I updated the skill incorporating your suggestions on reusable featurres/modules and attention-gym implementations.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

CLA Signed This label is managed by the Meta Open Source bot.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants