Skip to content

[GraphTrainer] Add memory policy registry and extra graph passes hook - #3215

Merged
SherlockNoMad merged 7 commits into
mainfrom
gh/syed-ahmed/3/head
May 7, 2026
Merged

SherlockNoMad merged 7 commits into
mainfrom
gh/syed-ahmed/3/head

Conversation

@syed-ahmed

@syed-ahmed syed-ahmed commented May 4, 2026 •

Copy link
Copy Markdown
Collaborator

Stack from ghstack (oldest at bottom):

  • Add AVAILABLE_MEMORY_POLICIES registry to passes.py so experiments can
    register custom memory policies without modifying graph_trainer code.
  • Refactor tag_with_memory_policy_pass to dispatch via the registry.
  • Change memory_policy config from Literal to str for extensibility.
  • Add _get_extra_graph_passes hook to GraphTrainer for subclasses to
    inject additional graph passes into the aot_fx_trace pipeline.

Co-Authored-By: Claude Opus 4.7 (1M context) [email protected]

- Add AVAILABLE_MEMORY_POLICIES registry to passes.py so experiments can
  register custom memory policies without modifying graph_trainer code.
- Refactor tag_with_memory_policy_pass to dispatch via the registry.
- Change memory_policy config from Literal to str for extensibility.
- Add _get_extra_graph_passes hook to GraphTrainer for subclasses to
  inject additional graph passes into the aot_fx_trace pipeline.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

[ghstack-poisoned]
cpu_offload_all: offload all eligible activations to CPU.
Work in progress — for development and testing only.

Experiments can register additional policies via

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.

Users can

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.

since we are not adding an experiment.

# from torchtitan.experiments.graph_trainer.passes import AVAILABLE_MEMORY_POLICIES
# AVAILABLE_MEMORY_POLICIES["my_policy"] = my_policy_fn
# Each policy is a callable: (gm, *, config) -> gm
AVAILABLE_MEMORY_POLICIES: dict[str, Callable] = {

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.

Nice.

Now I think all memory policy related pass can be its own memory_policy.py ?

Also a nice pattern for registry is

@register_memory_policy(name="default")
def _default_memory_policy_pass()
··· 

Neither comments are blocking tho, we can do it as follow up 

expected_fingerprint=config_fingerprint,
)

def _get_extra_graph_passes(self, model: nn.Module) -> list[tuple]:

@SherlockNoMad SherlockNoMad May 5, 2026 •

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.

now that we are not doing this as an experiment, I wonder if we still need this?

I think we will eventually need an API to customize graph passes.

insert_before works, but kinda hacky... so we would prefer we don't do this.

A more proper way to customize graph pass is to just directly construct the passes, and register it via registry.

e.g.

@register_pass_pipeline("default")
def compile_time_passes(...)

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

not fan of _get_extra_graph_passes

root added 2 commits May 5, 2026 20:17
…and extra graph passes hook"

- Add AVAILABLE_MEMORY_POLICIES registry to passes.py so experiments can
  register custom memory policies without modifying graph_trainer code.
- Refactor tag_with_memory_policy_pass to dispatch via the registry.
- Change memory_policy config from Literal to str for extensibility.
- Add _get_extra_graph_passes hook to GraphTrainer for subclasses to
  inject additional graph passes into the aot_fx_trace pipeline.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreplyanthropic.com>

[ghstack-poisoned]
…passes hook"

- Add AVAILABLE_MEMORY_POLICIES registry to passes.py so experiments can
  register custom memory policies without modifying graph_trainer code.
- Refactor tag_with_memory_policy_pass to dispatch via the registry.
- Change memory_policy config from Literal to str for extensibility.
- Add _get_extra_graph_passes hook to GraphTrainer for subclasses to
  inject additional graph passes into the aot_fx_trace pipeline.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreplyanthropic.com>

[ghstack-poisoned]
@syed-ahmed syed-ahmed changed the title [GraphTrainer] Add memory policy registry and extra graph passes hook [GraphTrainer] Add memory policy registry and pass pipeline hooks May 6, 2026
@syed-ahmed syed-ahmed changed the title [GraphTrainer] Add memory policy registry and pass pipeline hooks [GraphTrainer] Add memory policy registry and extra graph passes hook May 6, 2026
@syed-ahmed syed-ahmed changed the title [GraphTrainer] Add memory policy registry and extra graph passes hook [GraphTrainer] Add memory policy registry and pass pipeline hooks May 6, 2026
@syed-ahmed syed-ahmed changed the title [GraphTrainer] Add memory policy registry and pass pipeline hooks [GraphTrainer] Add memory policy registry and extra graph passes hook May 6, 2026
Comment on lines +86 to +87
POST_INIT_HOOKS: dict[type, Callable] = {}
PRE_TRAIN_STEP_HOOKS: dict[type, Callable] = {}

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.

I suppose these hooks are used in the latter PRs.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Yes.

PRE_TRAIN_STEP_HOOKS: dict[type, Callable] = {}


def _make_registry_decorator(registry: dict):

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.

nice

Comment on lines +25 to +43
@dataclass(kw_only=True, slots=True)
class DefaultMemoryPolicy:
"""Default SAC: save all compute-intensive ops and FSDP all_gathers."""

pass


@dataclass(kw_only=True, slots=True)
class EagerMemoryPolicy:
"""Eager SAC: alternate mm ops between save/recompute."""

pass


@dataclass(kw_only=True, slots=True)
class CpuOffloadAllMemoryPolicy:
"""Offload all eligible activations to CPU (WIP)."""

pass

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.

Wondering what are the benefit of declaring a class over "plain string"? is it for tyro?

"--compile.memory_policy cpu_offload_all",
"--parallelism.data_parallel_shard_degree 4",
"--parallelism.tensor_parallel_degree 2",
"compile.memory-policy:cpu-offload-all",

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.

hmm?

is this the new format for comment line arg? don't need -- anymore?

you might need to do a global replace for all use of compile.memory_policy in graph trainer

Comment on lines +50 to +74
_MEMORY_POLICY_TYPES: list = [
Annotated[DefaultMemoryPolicy, tyro.conf.subcommand("default")],
Annotated[EagerMemoryPolicy, tyro.conf.subcommand("eager")],
Annotated[CpuOffloadAllMemoryPolicy, tyro.conf.subcommand("cpu_offload_all")],
]


def register_memory_policy_config(name: str):
"""Register a memory policy config dataclass for CLI selection.

Use as a decorator on the policy dataclass. Call this before tyro parses
CLI args (i.e., at module import time).
The registered type becomes available as ``compile.memory_policy:<name>``.
"""

def decorator(cls: type) -> type:
_MEMORY_POLICY_TYPES.append(Annotated[cls, tyro.conf.subcommand(name)])
# Patch the annotation on GraphTrainerCompileConfig so tyro sees the
# updated Union when it parses CLI args.
GraphTrainerCompileConfig.__annotations__["memory_policy"] = Union[
tuple(_MEMORY_POLICY_TYPES)
]
return cls

return decorator

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.

hmm... seems complicated just for CLI support....
anything wrong with just plain string?


# Import paged stash registrations (registers additional policies + pipelines + hooks)
try:
import torchtitan.experiments.graph_trainer.paged_stash_memory_policy # noqa: F401, E402

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.

i suppose these are added in the future PRs.

Comment on lines 180 to 183
policy_type = type(self.config.compile.memory_policy)
pipeline_fn = PASS_PIPELINE_REGISTRY.get(
policy_type, construct_default_graph_passes
)

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 key here won't be memory_policy, it should be something general, and up for user to define.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Add a pass_pipeline key instead if that sounds ok?

def train_step(
self, data_iterator: Iterator[tuple[dict[str, torch.Tensor], torch.Tensor]]
):
policy_type = type(self.config.compile.memory_policy)

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.

same here, it's limiting to use memory_policy as key here.
This should allow arbitrary used-define type, or just plain string.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Same here, is a pass_pipeline key ok instead?

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

I think this mostly looks good, and I am signing this off so that you don't need another round of back-and-forth.

  1. I am not sure if we need to used type as the key for registry, str is simple is probably good enough.
  2. keys for pass_pipeline, and hooks shouldn't be memory_policy. It should support general user defined keys, i.e. string.

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

I think this mostly looks good, and I am signing this off so that you don't need another round of back-and-forth.

  1. I am not sure if we need to used type as the key for registry, str is simple is probably good enough.
  2. keys for pass_pipeline, and hooks shouldn't be memory_policy. It should support general user defined keys, i.e. string.

@SherlockNoMad SherlockNoMad added the ciflow/h100.8 Trigger H100.8 CI label May 6, 2026
syed-ahmed added 4 commits May 7, 2026 11:57
…and extra graph passes hook"


- Add AVAILABLE_MEMORY_POLICIES registry to passes.py so experiments can
  register custom memory policies without modifying graph_trainer code.
- Refactor tag_with_memory_policy_pass to dispatch via the registry.
- Change memory_policy config from Literal to str for extensibility.
- Add _get_extra_graph_passes hook to GraphTrainer for subclasses to
  inject additional graph passes into the aot_fx_trace pipeline.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreplyanthropic.com>

[ghstack-poisoned]
…passes hook"


- Add AVAILABLE_MEMORY_POLICIES registry to passes.py so experiments can
  register custom memory policies without modifying graph_trainer code.
- Refactor tag_with_memory_policy_pass to dispatch via the registry.
- Change memory_policy config from Literal to str for extensibility.
- Add _get_extra_graph_passes hook to GraphTrainer for subclasses to
  inject additional graph passes into the aot_fx_trace pipeline.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreplyanthropic.com>

[ghstack-poisoned]
…and extra graph passes hook"


- Add AVAILABLE_MEMORY_POLICIES registry to passes.py so experiments can
  register custom memory policies without modifying graph_trainer code.
- Refactor tag_with_memory_policy_pass to dispatch via the registry.
- Change memory_policy config from Literal to str for extensibility.
- Add _get_extra_graph_passes hook to GraphTrainer for subclasses to
  inject additional graph passes into the aot_fx_trace pipeline.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreplyanthropic.com>

[ghstack-poisoned]
…passes hook"


- Add AVAILABLE_MEMORY_POLICIES registry to passes.py so experiments can
  register custom memory policies without modifying graph_trainer code.
- Refactor tag_with_memory_policy_pass to dispatch via the registry.
- Change memory_policy config from Literal to str for extensibility.
- Add _get_extra_graph_passes hook to GraphTrainer for subclasses to
  inject additional graph passes into the aot_fx_trace pipeline.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreplyanthropic.com>

[ghstack-poisoned]
@syed-ahmed
syed-ahmed changed the base branch from gh/syed-ahmed/3/base to main May 7, 2026 21:09

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

Thanks!

@SherlockNoMad
SherlockNoMad merged commit bf2842d into main May 7, 2026
8 of 10 checks passed
SherlockNoMad added a commit that referenced this pull request Nov 4, 2026
…pile.extra_passes (#5827)

## Summary (human-written)
<!-- Write this yourself, not with an AI tool. 2-5 sentences: the
problem, why
     this approach, and what you checked yourself. -->

## Why
GraphTrainer has no way to add a graph pass without editing `passes.py`.
Model- or shape-specialized rewrites, such as replacing a traced
subgraph with a handwritten kernel, are wanted only by some recipes and
may live outside torchtitan, so they don't belong in the default
pipeline or behind a global flag. `compile.passes` already existed, but
nothing read it except the precompile fingerprint.

**Example.**
```python
# my_pkg/fusions.py -- any module, in or outside torchtitan
from torchtitan.experiments.graph_trainer.registry import register_graph_pass

@register_graph_pass
def my_kernel_fusion_pass(gm, example_inputs):
    ...  # replace matched subgraphs with calls to a custom op
    return gm

# recipe
from my_pkg.fusions import my_kernel_fusion_pass
config.compile.extra_passes = [my_kernel_fusion_pass.__name__]
```
The selected passes run in list order on the joint graph after the other
GraphTrainer passes, right before Inductor (pass log from the Llama 3
debug model):
```
   9. joint_transformer_block_bucketing_reordering_pass
  10. my_kernel_fusion_pass          <- compile.extra_passes
  11. annotate_flex_attention_for_regional_inductor_pass
  12. regional_inductor_pass
```

## What changed
- `registry.py`: `@register_graph_pass` and `GRAPH_PASS_REGISTRY`, keyed
by function name, which is also the name `extra_passes`,
`disable_passes`, and the pass log use. Registering a different function
under a taken name raises; re-importing the defining module does not.
- `passes.py`: `resolve_registered_graph_passes` raises `ValueError` for
unknown or repeated names. `compile_time_passes` appends the passes
after memory policy, remat, collective bucketing/reordering, and async
TP, right before the Inductor passes. SPMD, SPMD gradient accumulation,
GraphPP, and precompile all build their pass lists there; GraphPP and
SPMD gradient accumulation run them once on the joint graph before
splitting it into per-action graphs, so a fusion can match a forward
subgraph together with its backward.
- `trainer.py`: `GraphTrainingEngine.__init__` resolves the names, so a
typo fails before the model is built instead of at the first trace.
- Mechanical rename `compile.passes` -> `compile.extra_passes`:
`configs.py`, the precompile fingerprint key, and test helpers
(`_trainer_test_utils.py`, `test_bitwise_deterministic.py`,
`test_precompile.py`). Skimmable.
- Docs: "Registered Graph Passes" in the GraphTrainer README and a third
pass tier in `AGENTS.md` (the diff shows `.claude/CLAUDE.md`, which
`AGENTS.md` links to).

## Alternatives considered
- Trainer subclass hook (`_get_extra_graph_passes`, added in #3215 and
later removed): needs a trainer subclass per recipe and can't be
selected from config.
- `compile.pass_pipeline` / `PASS_PIPELINE_REGISTRY`: replaces the whole
pipeline, so each extension would copy the default pass list.
- Callables in the config instead of names: not serializable, and can't
be hashed into the precompile fingerprint.

## User-facing changes
| Before | After |
| --- | --- |
| `compile.passes` (read by nothing) | `compile.extra_passes`:
registered pass names, applied in order |
| Adding a pass means editing `passes.py` | `@register_graph_pass` in
any module, enabled per recipe |

Precompile fingerprints change (key renamed), so existing precompile
artifacts need regenerating.

## Numerics
No change for the default empty `extra_passes`: the pass list is
identical on `main` and this branch (12 passes, same order,
`graph_trainer_llama3_debugmodel`, 8x H100).

`scripts/loss_compare.py main <branch> --assert-equal
--no-seed-checkpoint` (seed 42, deterministic, 20 steps) cannot show
bitwise equality here, because this config is not bitwise reproducible
run to run on `main` either: running the same commit twice matches at
step 1, then drifts from step 2 on (~2e-6 at step 2, growing to ~1e-5),
the same magnitude as main vs branch.

| Comparison | Step 1 | Steps 2-20 |
| --- | --- | --- |
| main vs branch | identical | max abs diff 3.8e-5 (step 14) |
| branch vs branch (same commit, two runs) | identical | max abs diff
1.9e-5 (step 4) |

`test_bitwise_deterministic.py` passes.

## Testing
- New `tests/test_registry.py` (CPU): catches unknown or repeated names
being silently skipped, selected passes running out of order, and two
different passes registering under one name.
- 8x H100, torch `2.16.0.dev20261102+cu130`: `test_passes.py` +
`test_precompile.py` + `test_registry.py` 229 passed, 1 skipped;
`test_bitwise_deterministic.py` 16 passed, 9 skipped.
- End to end on the 1-GPU Llama 3 debug model, with a pass registered
from a module outside the repo: on SPMD it ran right before
`annotate_flex_attention_for_regional_inductor_pass`; on SPMD gradient
accumulation it ran once, last in the joint-graph passes, and not in the
per-action Inductor passes. Both trained normally.
- `pre-commit run` passes on the changed files.

## Known issues / follow-ups
- No in-repo pass registers yet; the first consumer (a kernel-fusion
pass) is a follow-up.
- `PASS_PIPELINE_REGISTRY` still has no registrants. If a custom
pipeline were selected, `extra_passes` would not apply. Candidate for
removal in a separate PR.
- Reproduce on `main`: `loss_compare.py`'s seed checkpoint fails for
GraphTrainer (`'GraphTrainingEngine' object has no attribute
'pp_schedule'`), and the GraphTrainer Llama 3 debug config is not
bitwise reproducible run to run under `loss_compare.py`.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/h100.8 Trigger H100.8 CI ciflow/8gpu CLA Signed This label is managed by the Meta Open Source bot.

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

2 participants