Skip to content

Make TorchTitan compile backend configurable - #5463

Merged
tianyu-l merged 1 commit into
pytorch:mainfrom
ryan-li-ryanllli-aws:ryanllli/configurable-local-compile-backend
Oct 28, 2026
Merged

tianyu-l merged 1 commit into
pytorch:mainfrom
ryan-li-ryanllli-aws:ryanllli/configurable-local-compile-backend

Conversation

@ryan-li-ryanllli-aws

@ryan-li-ryanllli-aws ryan-li-ryanllli-aws commented Oct 16, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Makes TorchTitan's local compile configuration extensible for out-of-tree device backends.

  • Replaces model.local_compile_regions: list[str] with model.local_compile: LocalCompileConfig.
  • LocalCompileConfig contains regions: list[str].
  • Moves local compile binding into LocalCompileConfig.apply().
  • Keeps Inductor as the base implementation.
  • Lets an out-of-tree backend subclass LocalCompileConfig to change the compilation behavior used by apply().

Motivation

TorchTitan owns several compile boundaries: named @local_compile regions, FlexAttention, and create_block_mask helpers. A caller can select a backend for a torch.compile call it owns, but that does not configure TorchTitan's internal compile sites.

The configuration object gives an out-of-tree backend one extension point without adding a backend name or backend-specific logic to upstream model configuration.

Design

The model config contains a LocalCompileConfig:

@dataclass(kw_only=True, slots=True)
class LocalCompileConfig:
    regions: list[str] = field(default_factory=list)

    def apply(self) -> None:
        ...

The base implementation uses PyTorch's default Inductor backend. apply() binds the selected named regions and TorchTitan's always-compiled FlexAttention and block-mask helpers.

An out-of-tree backend subclasses the config and overrides its static compile hook. The inherited apply() method then uses that backend-specific behavior for every TorchTitan-owned local compile boundary:

class CustomDeviceLocalCompileConfig(LocalCompileConfig):
    @staticmethod
    def _compile(reference, **compile_kwargs):
        compile_kwargs.pop("options", None)
        compile_kwargs["backend"] = "custom_device_backend"
        return torch.compile(reference, **compile_kwargs)


config.model.local_compile = CustomDeviceLocalCompileConfig(
    regions=["loss", "rope"],
)

Validation

Run with Python 3.11 and nightly CPU PyTorch:

python -m pytest -q \
  tests/unit_tests/cpu/config/test_compile_config.py \
  tests/unit_tests/cpu/config/test_context_parallel_validation.py \
  tests/unit_tests/cpu/models/deepseek_v3/test_deepseek_v3_mla_compile.py \
  tests/unit_tests/cpu/models/kimi_k3/test_kimi_k3_config.py \
  tests/unit_tests/cpu/models/qwen3_5/test_offset_rmsnorm.py \
  tests/unit_tests/cpu/test_trainer.py::test_graph_training_engine_rejects_local_compile
43 passed

The equivalent suite on the rebased upstream base passes 42 tests under the pre-refactor test name.

Also validated with Pyrefly (0 errors), ufmt, flake8, pydoclint, Python AST parsing, codespell, and git diff --check.

@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Oct 16, 2026
@pytorch-bot

pytorch-bot Bot commented Oct 16, 2026 •

Copy link
Copy Markdown

Workflows were awaiting approval. CI has now been triggered for the ciflow labels on this PR.

@ryan-li-ryanllli-aws
ryan-li-ryanllli-aws marked this pull request as ready for review October 16, 2026 22:15
@pytorch-bot pytorch-bot Bot added the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Oct 16, 2026

@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.

mind providing motivation / use cases before making such changes?

@ryan-li-ryanllli-aws

ryan-li-ryanllli-aws commented Oct 19, 2026 •

Copy link
Copy Markdown
Contributor Author

Updated in the PR description: To enable TorchTitan’s existing compile boundaries on out-of-tree device backends. A caller can specify torch.compile(..., backend="custom_device") for code it owns, but TorchTitan itself creates backend-less compile wrappers for named local regions, FlexAttention, and create_block_mask. Wrapping the model does not configure those internal compile sites.

Comment thread torchtitan/models/base/model.py Outdated
FlexAttention manages its own compilation and is not controlled by this list.
"""

local_compile_backend: str = "inductor"

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.

directionally does the following work for you

  • make local_compile_regions a LocalCompileConfig dataclass, which has a field regions: list[str]
  • turn apply compile into a method of the config apply() which still uses inductor as backend
  • out-of-tree: subclass LocalCompileConfig with your custom backend to modify apply() behavior

@ryan-li-ryanllli-aws ryan-li-ryanllli-aws Oct 20, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Thanks for reviewing, updated in commit 59d01db5b6 to use model.local_compile: LocalCompileConfig with regions and apply(), allowing out-of-tree subclasses to customize the compile behavior.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Done in commit f7a2a4b55e: model.local_compile is a LocalCompileConfig with regions and apply(), and out-of-tree subclasses can override _compile() for a custom backend.

Comment thread torchtitan/distributed/utils.py Resolved
Comment thread torchtitan/distributed/local_compile.py Outdated
self,
reference: Callable[..., Any],
*,
inductor_options: dict[str, Any] | None = None,

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.

why introducing this kwarg?

@ryan-li-ryanllli-aws ryan-li-ryanllli-aws Oct 27, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Done in commit f7a2a4b55e: removed the custom inductor_options kwarg and forwarded the standard torch.compile kwargs instead.


regions: list[str] = field(default_factory=list)

def _compile(

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.

should this be static method?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Done in commit f7a2a4b55e: made LocalCompileConfig._compile() a static method.

Comment thread torchtitan/distributed/local_compile.py Outdated
def compiled(
reference: Callable[..., Any],
*,
inductor_options: dict[str, Any] | None = None,

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.

don't need this as a separate arg?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Done in commit f7a2a4b55e: removed the separate compile-options argument; options now pass through the standard compile kwargs.

Comment thread torchtitan/distributed/local_compile.py Outdated


__all__ = ["apply_local_compile", "local_compile"]
def compiled(

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.

maybe just

Suggested change
def compiled(
def compile(

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Done in commit f7a2a4b55e: renamed the helper to compile().

_compiled_flex_attn: ClassVar[Callable] = torch.compile(
_compiled_flex_attn: ClassVar[Callable] = compiled(
flex_attention,
inductor_options=inductor_configs,

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.

don't need to change naming and order

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Done in commit f7a2a4b55e: restored the existing options= naming and the original argument order.

@ryan-li-ryanllli-aws
ryan-li-ryanllli-aws force-pushed the ryanllli/configurable-local-compile-backend branch from 59d01db to f7a2a4b Compare October 27, 2026 22:54
@pytorch-bot pytorch-bot Bot added the ciflow/b200 Trigger B200 CI label Oct 27, 2026
@tianyu-l
tianyu-l merged commit 0f9fd2b into pytorch:main Oct 28, 2026
35 of 36 checks passed
tianyu-l added a commit that referenced this pull request Oct 29, 2026
… route PRs to area experts (#5667)

## Why

PR volume has outgrown review capacity. Of the 1,429 PRs merged since
April, one maintainer approved 1,066 (75%), and October alone had 351
merged PRs. Many PRs are agent-generated, and the agents (and `@claude`)
follow `.claude/CLAUDE.md`, which in several places contradicts how PRs
are actually reviewed:

- Principle 5 says to flag BC breakage. The maintainers deliberately
don't promise BC.
- config.md says "emit a warning" when config is silently skipped.
Review comments almost always say "just error out".
- PR expectations say "new features need CPU unit tests at minimum". In
~1,000 reviews the maintainer almost never asked for a new unit test,
and often asked for tests to be removed or folded into existing ones.

The result: across 130 PRs, the current `@claude` cited CLAUDE.md at
least 38 times, mostly to escalate. That produced 16+ BC concerns, 9+
"add a warning" suggestions and 23+ test requests. It also missed the
most common real review question: should this change exist in this form
at all?

This PR rewrites the rules from what reviewers actually say. The source
data:
- 3,391 inline comments, 289 review bodies and 383 PR comments from
Jul-Oct 2026.
- 48 refactor PRs, used to extract structural preferences.
- A comparison of 196 `@claude` runs against the human review on the
same PRs.

It then adds a torchtitan review skill, builds on PyTorch's `pr-review`
skill, and routes PRs to area experts without making them blocking
owners.

**Example: one past PR, as reviewed by the new skill** (#5546, at the
commit that was originally reviewed; blind, with no access to the real
comments):

```
Verdict: Request changes -- The problem is real, but the fix swaps a hard error for a
warn-and-continue fallback to FA2 ... It also adds a head-dim hook to 9 call sites,
7 of which can never fire.
Must fix
1. torchtitan/tools/utils.py:95-104 -- a missing wheel on Hopper/Blackwell now means a
   warning plus a silent switch to a slower kernel with different numerics ...
   Smallest fix (~15 lines): ... raise a clear error that names the module to install.
```
The human review of that PR: "450 LoC PR for a safety check sounds
insane" and "can we error out -- we don't want people to implicitly get
bad perf".

## What changed

**1. Rules** (`.claude/CLAUDE.md`, `.claude/rules/`):
- Core principles rewritten:
  - start from the problem, not the patch;
  - minimal by default;
  - PyTorch-native and upstream first;
  - reuse, but don't bend shared code for one consumer;
  - keep core oblivious to features;
- no BC promises, but protect numerics, HF loading, metric keys and
main-path perf;
  - raise instead of warn;
  - hardware-agnostic.
- Naming additions: overloaded terms, one name per concept, `_private`.
- PR expectations: descriptions must convince a human; tests must earn
their cost; one concern per PR.
- `config.md` rewritten:
  - each component owns its `X.Config`;
  - select implementations by config type;
  - `X.Config | None` instead of `enable_*`;
  - no post-hoc config mutation;
  - few knobs;
  - validate in `__post_init__`.
- `distributed.md`: spmd_types first, parallelism combinations, hidden
D2H syncs, hardware.
- New rules files:
  - `design.md`: structural rules distilled from past refactors.
- `tests.md`: when to add tests, preferring extensions of existing
coverage, placement, golden files.
- `direction.md`: current migrations. This needs maintainers to keep it
current.

**2. `pr-review` skill** (`.claude/skills/pr-review/`):

| Step | What it does |
| --- | --- |
| Context | Applicable rules, maintainer comments addressed or not,
earlier bot findings, overlapping open PRs. |
| Necessity/design gate | Is the problem real on main? Root cause vs
symptom? Right layer, or upstream? Should torchtitan own this?
Superseded? Smallest alternative? Value evidence? |
| Deep review | A quick sweep of every hunk (scope, placement, new knobs
and tests), then the checklist, split by lens for large PRs. |
| Consolidate and fact-check | Dedupe by root cause and fix; drop BC,
"add a warning", generic "add tests", lint and praise; verify must-fix
items. |
| Output | Verdict first, plain-words summary, a concrete before/after
example, at most a few must-fix items, details collapsed, unverified
claims labeled. |
| Modes | Full review, "review again" (only the delta), "review my
review", or answer a specific question first. |
| Posting | Line-anchored findings as inline comments (with `suggestion`
blocks for small fixes, at most ~10, posted only by the main agent after
fact-check), then one formal review via `gh pr review` (`--approve` /
`--request-changes` / `--comment`) with the verdict and one-line
pointers. |

**3. PR descriptions:**
- `pr-description` skill and `.github/pull_request_template.md`: Why
(with a simple example) -> What changed -> user-facing before/after ->
numerics -> testing.
- CONTRIBUTING.md updated to match.

**4. `@claude` workflow** (`claude-code.yml`):
- Always uses the skill.
- Allows read-only `gh issue view` / `gh pr view` / `gh pr diff` / `gh
pr list`, plus `gh pr review` and the action's inline-comment tool (it
cannot approve). `gh api` stays blocked.
- `effort=low|max` and `fable` comment keywords; default effort `high`.
- 55-minute timeout.

**5. Review routing:**
- `CODEOWNERS`:
- `*`: `tianyu-l` `fegin` `wwwjn` `shuhuayu` `acisseJZhong`
`felipemello1`.
- graph_trainer paths: core plus `SherlockNoMad` `aditvenk`
`sanketpurandare`.
  - torchft paths: core plus `d4l3k`.
- Every path has an owner, so a bot approval can never satisfy branch
protection on its own.
- `.github/area_reviewers.yml` and `workflows/area_reviewers.yml`
request at most 3 area experts as non-blocking reviewers, based on which
areas the changed files touch. The workflow runs on
`pull_request_target`, reads only the file list through the API, and
never checks out PR code.

## Alternatives considered

- **Copy PyTorch's skill as-is.** Its "missing tests -> Request Changes"
and BC section are exactly what produced noise here.
- **PyTorch-style per-directory `REVIEW.md` files.** The existing
glob-scoped `.claude/rules/` already do this, without more `.md` sprawl.
- **Deterministic lint hooks** for `torch.cuda.*`, `isinstance(..,
DTensor)` and `enable_*` fields. Every pattern already has hits on main
(12, 15 and 7 files), so they would need allowlists. The skill checks
them on the diff instead.
- **Making area experts code owners.** That makes them blocking;
auto-requesting reviews routes PRs without adding gates.

## Testing

**Backtest.** The new skill reviewed 7 past PRs blind, each at the
commit that was originally reviewed, and the output was compared with
the real human review. The skill was then fixed for the misses, and the
affected cases were re-run.

| PR | Human review's main point | New skill |
| --- | --- | --- |
| #5546 | too big for a safety check; error out | Hit both |
| #5153 | does this happen on main? don't violate the `nn.Module`
contract | Hit; proposed the fix that eventually landed |
| #4754 | workaround, not a fix; move the test | Hit the root cause (the
same fix the author later proposed); missed the test move, now covered
by the sweep |
| #5463 | motivation first; `LocalCompileConfig` design | Hit the design
and unused kwargs; motivation is a must-fix after the re-run |
| #5183 | NCCL-specific knob in core; TODO; `<0` semantics | Hit |
| #4474 | approve; DSv4 should fix the model/loss | Approve; partly
raised the model point |
| #4421 | approve; "how much e2e?" | Originally requested changes;
approves with items after the re-run |

None of the 10 reviews raised BC or asked for a warning.

**Other checks:**
- **Reviewer routing:** the area-reviewer logic was replayed on 1,429
merged PRs. Peak load is about 50 requests/month per person (graph
trainer, PP, MoE).
- **Workflow script:** dry-run with mocked GitHub objects on a real PR's
file list. The author is excluded, existing reviewers are skipped, and a
non-collaborator failure doesn't fail the run.
- **YAML and lint:** all YAML parses, the inline JS passes `node
--check`, and `pre-commit` passes.

## Known issues / follow-ups

- Comment-triggered workflows run from `main`, so `claude-code.yml` and
the skill only take effect after merge. Try `@claude review` on a real
PR right after.
- Not verified: whether the Claude GitHub App has write access. If it
does, its approvals count toward the 1 required approval (but never as a
code-owner approval), and its REQUEST_CHANGES blocks merging until it
re-approves or someone dismisses it. If it doesn't, its reviews are
advisory. The first real review will show which.
- `direction.md` and `area_reviewers.yml` are only useful if they are
kept current.
- Not included:
- PyTorch's time-budget hook (reviews that hit the 55-minute limit are
lost);
- auto-review on every push, which needs the PyTorch CI owners' hardened
setup.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/b200 Trigger B200 CI ciflow/fake-pg Run 1-GPU Fake PG integration tests ciflow/rl 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.

2 participants