Repository navigation
[GraphTrainer] Add memory policy registry and extra graph passes hook - #3215
Conversation
- 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 |
There was a problem hiding this comment.
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] = { |
There was a problem hiding this comment.
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]: |
There was a problem hiding this comment.
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
left a comment
There was a problem hiding this comment.
not fan of _get_extra_graph_passes
…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]
| POST_INIT_HOOKS: dict[type, Callable] = {} | ||
| PRE_TRAIN_STEP_HOOKS: dict[type, Callable] = {} |
There was a problem hiding this comment.
I suppose these hooks are used in the latter PRs.
| PRE_TRAIN_STEP_HOOKS: dict[type, Callable] = {} | ||
|
|
||
|
|
||
| def _make_registry_decorator(registry: dict): |
| @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 |
There was a problem hiding this comment.
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", |
There was a problem hiding this comment.
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
| _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 |
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
i suppose these are added in the future PRs.
| policy_type = type(self.config.compile.memory_policy) | ||
| pipeline_fn = PASS_PIPELINE_REGISTRY.get( | ||
| policy_type, construct_default_graph_passes | ||
| ) |
There was a problem hiding this comment.
the key here won't be memory_policy, it should be something general, and up for user to define.
There was a problem hiding this comment.
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) |
There was a problem hiding this comment.
same here, it's limiting to use memory_policy as key here.
This should allow arbitrary used-define type, or just plain string.
There was a problem hiding this comment.
Same here, is a pass_pipeline key ok instead?
SherlockNoMad
left a comment
There was a problem hiding this comment.
I think this mostly looks good, and I am signing this off so that you don't need another round of back-and-forth.
- I am not sure if we need to used type as the key for registry, str is simple is probably good enough.
- keys for pass_pipeline, and hooks shouldn't be memory_policy. It should support general user defined keys, i.e. string.
SherlockNoMad
left a comment
There was a problem hiding this comment.
I think this mostly looks good, and I am signing this off so that you don't need another round of back-and-forth.
- I am not sure if we need to used type as the key for registry, str is simple is probably good enough.
- keys for pass_pipeline, and hooks shouldn't be memory_policy. It should support general user defined keys, i.e. string.
…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]
…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`.
Stack from ghstack (oldest at bottom):
register custom memory policies without modifying graph_trainer code.
inject additional graph passes into the aot_fx_trace pipeline.
Co-Authored-By: Claude Opus 4.7 (1M context) [email protected]