Repository navigation
[Paged Stash] CUDA-graphable MoE with paged activation stashing - #3216
Conversation
Paged stash SAC for MoE expert activations: pre-allocated paged buffers store dynamic-shaped _grouped_mm outputs for the backward pass, avoiding both recomputation cost and memory fragmentation from variable token counts. - Joint-graph pass (paged_stash_graph_pass.py): inserts paged_stash.copy/pop ops using ao's stream infrastructure, redirecting backward consumers through paged buffers so SAC+remat naturally ignores stashed activations. - PagedStashTrainer (train.py): extends GraphTrainer with 3-level overflow defense (host spillover, cross-rank detection, retry with buffer growth). - Memory policy registration: paged_stash and paged_stash_save_only policies. - Fine-grained annotation via annotate_fn on _run_experts_grouped_mm. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> [ghstack-poisoned]
| """Check if HybridEP dispatch exceeded capacity budget (tokens dropped). | ||
|
|
||
| Returns a GPU bool tensor. Safe to call after the training step completes | ||
| (the .item() D2H sync is acceptable post-step). |
There was a problem hiding this comment.
for graph trainer, training step includes optimizer, so weights are already updated by the time this is checked, maybe we can do the checks on device for then
There was a problem hiding this comment.
Agreed. Currently have a pre-train step hook (register_pre_train_step_hook) that raises a runtime error after the full train step when overflow is detected (so weights are probably still updated). Will look into how to do a check on device.
There was a problem hiding this comment.
Done. The default compile.paged_stash.overflow_check = "deferred" never syncs. Each step copies its overflow and token-drop flags to pinned host memory asynchronously, and a later step reads them. Meanwhile, every optimizer step all-reduces the overflow flag on device and passes it to fused Adam/AdamW as AMP's found_inf. So a step whose stash overflowed is skipped on device before it can touch the parameters, optimizer state or MoE expert biases, and the job then fails when the flag is read. blocking mode (Megatron's) reads the verdict before the optimizer runs and reruns the step with paging disabled.
| in PagedStashTrainer.Config) and left as defaults; callers should | ||
| explicitly set them via ``_apply_aot_fx_trace_defaults``. | ||
| """ | ||
| from torchtitan.experiments.cuda_graphable_moe.train import PagedStashTrainer |
There was a problem hiding this comment.
why don't we move the config class here to avoid the circular import
There was a problem hiding this comment.
This is now outdated. Paged Stash config is moved to:
from torchtitan.experiments.graph_trainer.paged_stash_memory_policy import PagedStash
It's now imported in graph_trainer config.
| # all parameters to participate in forward. ChunkedCELoss sets | ||
| # _skip_lm_head=True making lm_head.weight unused in the traced graph. | ||
| if isinstance(d.get("loss"), ChunkedCELoss.Config): | ||
| d["loss"] = CrossEntropyLoss.Config() |
There was a problem hiding this comment.
would recommend this to be configured explicitly or at least to fail loudly
There was a problem hiding this comment.
This is now outdated and not part of this PR.
|
I will review when this is in graph_trainer |
| def _is_moe_fc1_grouped_mm(node: fx.Node) -> bool: | ||
| """Check if a node is a MoE fc1 (gate or up) ``_grouped_mm`` output. | ||
|
|
||
| Matches ``aten._grouped_mm.default`` nodes that are part of the SwiGLU |
There was a problem hiding this comment.
i think it will be _scaled_grouped_mm for ao mxfp8
There was a problem hiding this comment.
Agreed, is it ok to leave a TODO and first integrate MXFP8 with graph_trainer and then update this pass to account for the scaled_grouped_mm?
There was a problem hiding this comment.
The pass now pages every activation backward reads inside the annotated expert region, whatever op produced it. So a fused MXFP8 expert MLP is covered without naming its ops: its quantized FC1/FC2 inputs, their e8m0 block scales, and its FC1 output are all stashed. test_annotated_region_is_paged[mxfp8] exercises that.
| A node is eligible when all of: | ||
| 1. It is a forward ``call_function`` node. | ||
| 2. It is an ``aten._grouped_mm`` whose consumer is ``silu`` or ``mul`` | ||
| (MoE fc1 gate/up projection, identified by op-target + consumer pattern). | ||
| 3. It has real (non-sym) backward consumers. | ||
| 4. It has a dynamic SymInt first dimension. | ||
| 5. Its ``(dtype, shape[-1])`` matches a pre-allocated paged buffer. |
There was a problem hiding this comment.
I'm not sure i understand the need for pattern matching. Naively I would of thought to grab all nodes between dispatch/combine nodes, then to check which ones are activations (used outside of those nodes). And any activations having an unbacked shape due to received number of tokens should be paged
There was a problem hiding this comment.
we could rely on annotations instead too
There was a problem hiding this comment.
Yeah, I'm totally open to what to do here. I was trying to match exactly the activations Megatron applies paged stashing to (expert_fc1, moe_act, expert_fc2). Note that, megatron uses Swiglu fused grouped mlp: NVIDIA/TransformerEngine#2769, so the approach we use - pattern matching vs annotation - can affect how many activations get picked up for paged stashing. I guess The main filter is unbacked shape, which should decide whether it should be paged stashed or not.
There was a problem hiding this comment.
Follow-up: switched to annotations, as you suggested. compile.paged_stash.module_fqn (default layers.*.moe.routed_experts) marks the region before tracing, and the pass stashes every activation in it that backward reads and the stash can hold. Which ones qualify is read off the dispatcher's static capacity, as you described; there's no pattern matching. A padded activation that still crosses into backward unpaged gets a warning naming it.
…shing" Paged stash SAC for MoE expert activations: pre-allocated paged buffers store dynamic-shaped _grouped_mm outputs for the backward pass, avoiding both recomputation cost and memory fragmentation from variable token counts. - Joint-graph pass (paged_stash_graph_pass.py): inserts paged_stash.copy/pop ops using ao's stream infrastructure, redirecting backward consumers through paged buffers so SAC+remat naturally ignores stashed activations. - PagedStashTrainer (train.py): extends GraphTrainer with 3-level overflow defense (host spillover, cross-rank detection, retry with buffer growth). - Memory policy registration: paged_stash and paged_stash_save_only policies. - Fine-grained annotation via annotate_fn on _run_experts_grouped_mm. - Comparison with Megatron's implementation here: https://gist.github.com/syed-ahmed/f82d8485007eef91e90f08f24607d940 Co-Authored-By: Claude Opus 4.7 (1M context) <noreplyanthropic.com> [ghstack-poisoned]
IvanYashchuk
left a comment
There was a problem hiding this comment.
I like the direction of this PR. It matches the production path we have been seeing for MoE graphability: avoid conditional graph nodes, make the dispatch/expert path graph-compatible, and use paged storage to avoid worst-case activation memory across layers.
The parts I would fix before relying on this for real training experiments are correctness-related. Paged-stash overflow and HybridEP non-blocking capacity overflow both need to be caught before optimizer state is updated, and probably the check should be collective across ranks. Also, the mutation should be explicit enough that later graph passes cannot reorder or drop it.
The integration test is useful, and top-of-stack CI being green is a good signal. I would still add focused tests for graph surgery, copy/pop ordering, overflow-before-optimizer behavior, and multi-rank overflow before treating this as more than an experimental path.
| """Check previous step's overflow flag, then reset buffers for this step.""" | ||
| for model_part in trainer.model_parts: | ||
| overflow = getattr(model_part, "_paged_stash_overflow", None) | ||
| if overflow is not None and overflow.item() != 0: |
There was a problem hiding this comment.
This check looks too late for correctness. The copy kernel can set overflow during the current forward/backward, and the comment above page_record says the data may be wrong and the step will be retried. But this hook runs at the start of the next train_step, after the previous step may have already run backward and updated optimizer state with corrupted gradients.
Can we move this check before optimizer update and make it collective across ranks? If the intended behavior is retry, I think we need an explicit skip/retry path before optimizer state changes. If this is fail fast, the comment about overflow gradients being thrown away should change.
There was a problem hiding this comment.
so in the graph trainer, we will want to have the whole training step including the optimizer in a single fx/cuda graph. if there's no way to delay the cpu sync from the .item check, we could consider having a device-side check
There was a problem hiding this comment.
Agreed, and fixed. An overflow can no longer reach the optimizer state, and the check is collective. There are two modes:
deferred, the default. Every optimizer step all-reduces the overflow flag on device and passes it to fused Adam/AdamW asfound_inf. So every rank skips the update of an overflowed step, and its expert-bias update is undone, without a host sync. The rank that overflowed raises once it reads its flag a step or two later, and a blocking read at shutdown covers the final steps. Deferred mode rejects optimizers that can't skip on device.blocking, Megatron's. It reads the all-reduced verdict before the step returns and reruns an overflowing step with paging disabled. Under CUDA graphs the rerun first drops the captured graphs.
Tests: test_deferred_mode, test_deferred_mode_skips_overflowed_optimizer_steps, test_blocking_mode.
| ) | ||
|
|
||
|
|
||
| def check_hybridep_over_budget() -> torch.Tensor: |
There was a problem hiding this comment.
This helper records an important correctness condition, but I do not see it wired into GraphTrainer or the paged-stash policy. In non-blocking mode, HybridEP can silently drop tokens when the capacity budget is exceeded. The dispatcher docs say the overflow flag is set on GPU, but this PR does not appear to enforce it before optimizer update.
Can we check this in the same pre-optimizer path as paged-stash overflow? If reduced capacity factors are only meant for debugging, I think we should require an explicit "allow dropped tokens" flag rather than making silent token drops possible in a training run.
There was a problem hiding this comment.
It's wired in now. Every non-blocking dispatch ORs its overflow flag into a persistent flag, which also works under CUDA graph replay. The paged-stash runner folds that flag into the same per-step verdict as stash overflow, the "overbudget" slot of Megatron's check, and reports it each step. It doesn't fail the step. The capacity factor is compiled into the graph, so a rerun would drop the same tokens again: Megatron reruns with the capacity cleared, which a captured graph can't do. A drop also doesn't corrupt anything; it's the capacity factor's documented behaviour. I'd keep enforcing it (an explicit "allow dropped tokens" flag) as a follow-up that covers non-blocking HybridEP in general, not just paged stashing.
| @torch.library.custom_op( | ||
| "paged_stash::copy", | ||
| mutates_args=(), | ||
| ) |
There was a problem hiding this comment.
Do we need to make the free-list mutation explicit in the graph? paged_stash.copy and paged_stash.pop both mutate global buffer/free-list state through _PAGED_STASH_REGISTRY, but the custom op schema says mutates_args=(), and the returned head/tail state is not threaded into later copy/pop ops.
Page allocation order is correctness-critical. Can we either thread an explicit state token/free-list state through the graph, or mark/model these ops as side-effectful in a way AOT partitioning and later graph passes respect? At minimum, I think we need a test that inspects the transformed graph and replays multiple layers to prove copy/pop ordering survives the full pass pipeline. @kshitij12345, could you please review this part? What are the best practices for mutation and new custom_ops?
There was a problem hiding this comment.
Sorry, I missed the ping here.
mutates_args (Iterable[str] or "unknown") – The names of args that the function mutates. This MUST be accurate, otherwise, the behavior is undefined. If “unknown”, it pessimistically assumes that all inputs to the operator are being mutated.
As Ivan pointed out, the compiler is free to reorder operations that are pure (which mutates_args=() implies).
To fix this,
- Thread the state tensors explicitly: As mentioned by Ivan, pass
free_list_headandoverflowas args tocopy,free_list_tailandoverflowtopop, with correctmutates_args. This gives the compiler clear picture about which tensors are mutated. The tradeoff is that these tensors need to appear in the graph (viaget_attr/register_buffer), which may conflict with the DTensor/deepcopy concerns mentioned in the registry comment. Registering them as non-persistent buffers (persistent=False) may help. - mutates_args="unknown": Pessimistically tells the compiler all inputs may be mutated, preventing reordering past anything that could alias. Avoids the DTensor/deepcopy issue since no new graph tensors are introduced, but may inhibit other valid optimizations since the compiler treats every input as potentially mutated.
There was a problem hiding this comment.
The ops were redesigned so ordering is carried by the graph:
paged_stash::stash_declares its mutation (mutates_args=("handle",)): it writes the page record into a handle the graph allocates, so it's impure and can't be dropped or moved past the reload that reads that handle.reloadtakes the handle as input, so it can't move before its stash.wait_reloadandreload_nextare registered withhas_side_effect.- The freelist stays manager state, as in Megatron, rather than graph tensors (the DTensor/deepcopy concern). That's safe because correctness doesn't depend on the order of different stashes and reloads. Each stash records its own pages in its handle, and all copies and pops run on one side stream in launch order, so freelist updates are serialized.
Tests that inspect the transformed graph and replay it:
test_pass_places_megatron_stash_points: where each op lands;test_graphpp_partition_keeps_stashes_in_forward_and_reloads_in_backward: the forward/backward split;test_round_trip_is_exactandtest_host_spill_and_overflow: multi-slot replays inside a captured CUDA graph;test_reloads_are_prefetched_one_schedule_entry_ahead: ordering across pipeline actions.
| # --------------------------------------------------------------------------- | ||
|
|
||
|
|
||
| def _is_moe_fc1_grouped_mm(node: fx.Node) -> bool: |
There was a problem hiding this comment.
This matcher seems narrower than the PR description. It picks bf16 aten._grouped_mm.default fc1 gate/up patterns by consumer shape, but not the SiLU output, the post-SwiGLU product, fc2-related activations, or _scaled_grouped_mm for AO/MXFP8. The buffer sizing also looks broader than the two grouped-mm outputs that are currently matched.
Can we define the exact set this policy owns and add a graph-pass test that asserts which nodes are stashed for the current bf16 path? Longer term, annotations around the expert region may be easier to maintain than consumer-pattern matching, especially for fused TransformerEngine/AO paths.
There was a problem hiding this comment.
Agreed on both counts; it's annotation-based now (see the reply to xmfan above), and the set it owns is defined and tested. For the stock BF16 SwiGLU experts it pages:
- the dispatch output;
- the fused gate/up projection;
- the SiLU;
- the gate product;
- the down projection's output.
For a fused MXFP8 expert MLP it pages everything the composite saves, plus its output. test_annotated_region_is_paged asserts both sets exactly, and the slot shape of each. Buffers are sized from what's actually stashed: one pool per (dtype, hidden_size), measured on the first step and replayed over the PP schedule.
| # integer constant -- no buffer tensors appear as graph arguments, get_attr | ||
| # nodes, or placeholders. This avoids deepcopy and DTensor issues entirely. | ||
|
|
||
| _PAGED_STASH_REGISTRY: dict[int, "PagedStashBuffer"] = {} |
There was a problem hiding this comment.
Can we add an explicit cleanup path for this registry? _PAGED_STASH_REGISTRY and _PAGED_STASH_BUFFERS_DICT hold large CUDA/host buffers in module-level global state, and unregister_paged_stash_buffer() exists but is not used. That is probably okay for one trainer per process, but brittle for tests, repeated trainer construction, or long-running processes that switch configs.
I would either clear the paged-stash registry from GraphTrainer.close() for this policy, or document the single-trainer lifetime assumption and add a small test that constructs/closes two paged-stash trainers in one process without stale buffers.
There was a problem hiding this comment.
The module-level registries are gone: the buffers and their sizing state live in one PagedStashManager. GraphTrainingEngine.close() now releases it via PagedStashManager.reset_instance(), so a second trainer in the same process starts clean. The unit tests already reset it between tests.
…shing" Paged stash SAC for MoE expert activations: pre-allocated paged buffers store dynamic-shaped _grouped_mm outputs for the backward pass, avoiding both recomputation cost and memory fragmentation from variable token counts. - Joint-graph pass (paged_stash_graph_pass.py): inserts paged_stash.copy/pop ops using ao's stream infrastructure, redirecting backward consumers through paged buffers so SAC+remat naturally ignores stashed activations. - PagedStashTrainer (train.py): extends GraphTrainer with 3-level overflow defense (host spillover, cross-rank detection, retry with buffer growth). - Memory policy registration: paged_stash and paged_stash_save_only policies. - Fine-grained annotation via annotate_fn on _run_experts_grouped_mm. - Comparison with Megatron's implementation here: https://gist.github.com/syed-ahmed/f82d8485007eef91e90f08f24607d940 Co-Authored-By: Claude Opus 4.7 (1M context) <noreplyanthropic.com> [ghstack-poisoned]
…shing" Paged stash SAC for MoE expert activations: pre-allocated paged buffers store dynamic-shaped _grouped_mm outputs for the backward pass, avoiding both recomputation cost and memory fragmentation from variable token counts. - Joint-graph pass (paged_stash_graph_pass.py): inserts paged_stash.copy/pop ops using ao's stream infrastructure, redirecting backward consumers through paged buffers so SAC+remat naturally ignores stashed activations. - PagedStashTrainer (train.py): extends GraphTrainer with 3-level overflow defense (host spillover, cross-rank detection, retry with buffer growth). - Memory policy registration: paged_stash and paged_stash_save_only policies. - Fine-grained annotation via annotate_fn on _run_experts_grouped_mm. - Comparison with Megatron's implementation here: https://gist.github.com/syed-ahmed/f82d8485007eef91e90f08f24607d940 Co-Authored-By: Claude Opus 4.7 (1M context) <noreplyanthropic.com> [ghstack-poisoned]
…#3215) Stack from [ghstack](https://github.com/ezyang/ghstack) (oldest at bottom): * #3218 * #3217 * #3216 * __->__ #3215 - 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]> --------- Co-authored-by: root <[email protected]>
| if _fn is selective_activation_remat_pass: | ||
| new_passes.append(bound_pass) | ||
| new_passes.append(p) |
There was a problem hiding this comment.
How is the compatibility between paged_stash_pass and apply_cpu_offload_pass?
Probably need some pre-caution here
There was a problem hiding this comment.
The two passes are now mutually exclusive. Inside the paged-stash region, paged stashing decides, overriding any MUST_CPU_OFFLOAD tag (per your later comment), so apply_cpu_offload_pass never sees those nodes. Outside the region, paged stashing touches nothing. The paged-stash pass runs after CPU offload and remat; passes.py has a comment on why.
| def paged_stash_pass( | ||
| gm: torch.fx.GraphModule, | ||
| example_inputs: tuple | None = None, | ||
| *, | ||
| paged_buffers: dict[tuple[torch.dtype, int], "PagedStashBuffer"], | ||
| ) -> torch.fx.GraphModule: | ||
| """Paged stash pass for the ``aot_fx_trace`` compile-time pass list. | ||
|
|
||
| Inserts ``paged_stash.copy/pop`` + ``ao.wait_tensor`` ops for eligible | ||
| activations. Must run **before** ``selective_activation_remat_pass`` so | ||
| that backward consumers are already redirected when SAC + remat runs -- | ||
| the original activations have no backward users and are naturally ignored | ||
| by rematerialization. | ||
| """ | ||
| return apply_paged_stash_pass(gm, paged_buffers) |
There was a problem hiding this comment.
This layer of wrapping doesn't seem necessary?
you can directly make apply_paged_stash_pass comply with the graphpass signature
There was a problem hiding this comment.
Done: apply_paged_stash_pass(gm, example_inputs, *, page_size, prefetch_lookahead) follows the graph-pass signature directly and is bound with functools.partial in compile_time_passes.
| # Module-level state for pass pipeline access | ||
| # --------------------------------------------------------------------------- | ||
|
|
||
| _PAGED_STASH_BUFFERS_DICT: dict | None = None |
There was a problem hiding this comment.
have a word about the basic structure of this dict?
type annotation is also helpful
There was a problem hiding this comment.
That module-level dict is gone. The buffers are PagedStashManager.stash_buffers, typed as dict[tuple[torch.dtype, int], PagedStashBuffer]: one pool of fixed-size pages per (dtype, hidden_size), shared by every layer.
…shing" Paged stash SAC for MoE expert activations: pre-allocated paged buffers store dynamic-shaped _grouped_mm outputs for the backward pass, avoiding both recomputation cost and memory fragmentation from variable token counts. - Joint-graph pass (paged_stash_graph_pass.py): inserts paged_stash.copy/pop ops using ao's stream infrastructure, redirecting backward consumers through paged buffers so SAC+remat naturally ignores stashed activations. - PagedStashTrainer (train.py): extends GraphTrainer with 3-level overflow defense (host spillover, cross-rank detection, retry with buffer growth). - Memory policy registration: paged_stash and paged_stash_save_only policies. - Fine-grained annotation via annotate_fn on _run_experts_grouped_mm. - Comparison with Megatron's implementation here: https://gist.github.com/syed-ahmed/f82d8485007eef91e90f08f24607d940 AI assistant used: Claude Opus 4.7 (1M context) <noreplyanthropic.com> [ghstack-poisoned]
| torch.ops.paged_stash.stash_.default, | ||
| torch.ops.paged_stash.wait_stash_.default, | ||
| torch.ops.paged_stash.reload.default, | ||
| torch.ops.paged_stash.wait.default, |
There was a problem hiding this comment.
Renamed to paged_stash::wait_reload, so the backward pair reads reload / wait_reload. Note, the forward side has no wait any more - see response to comment below on scheduling where the stash's copy is joined at the next layer's group_start, to keep things exactly as how Megatron does it for now. The code before was using the design patterns from cpu offload pass and I decided to just follow Megatron for now.
| policy = node.meta.get("recompute") | ||
| if policy in ( | ||
| CheckpointPolicy.MUST_RECOMPUTE, | ||
| CheckpointPolicy.PREFER_RECOMPUTE, | ||
| ): | ||
| continue | ||
| if policy == CheckpointPolicy.MUST_CPU_OFFLOAD: | ||
| # Already claimed by the CPU offload pass; do not page it twice. | ||
| continue |
There was a problem hiding this comment.
I think you should just ignore the prior tags in the MoE region?
If user opt-in to use paged stashing, it should have full control over what to recompute/save/stash over the MoE region.
you should have the freedom to override the prior recompute/offload decision.
There was a problem hiding this comment.
Agreed, and that's how it works now. Opting into sac_and_paged_stash hands the paged stash the annotated region outright.
- Before tracing,
build_paged_stash_runnerannotates the modules matchingcompile.paged_stash.module_fqn(defaultlayers.*.moe.routed_experts) withannotate_paged_stash_region. It uses the sameannotate_fnmechanism asannotate_module_fqns, so every node traced inside those modules, submodules included, carriesPAGED_STASH_REGIONinnode.meta["custom"]. tag_paged_stash_activationsthen stashes every activation in that region that backward reads and the stash can hold, and marks itMUST_SAVE, whatever SAC or CPU offload tagged before.- Nothing inside the region has to declare anything. The pass reads each activation's row layout off its shape, or off a reshape of it (e.g. a flattened block-scale buffer). If backward still ends up reading a padded activation unpaged, for example because remat rebuilds something the stash couldn't hold, the pass warns and names it.
Behavior covered by test_annotated_region_is_paged, for the stock BF16 and a fused MXFP8 expert MLP (including overriding a MUST_CPU_OFFLOAD tag), and test_region_annotation_covers_the_module_subtree.
| # Only activations that survive into backward are worth paging. | ||
| _, has_backward = _get_storage_chain(node) | ||
| if not has_backward and not any(_is_backward_node(u) for u in node.users): | ||
| continue |
There was a problem hiding this comment.
I would make it explicit here what's stashed vs. what's recomputed.
for example, output of dispatch is stashed, and everything else recomputed.
There was a problem hiding this comment.
Made explicit in tag_paged_stash_activations's docstring. The rule is that annotating a region means paging it - inside the region, everything backward reads that the stash can hold is stashed, and none of it is recomputed.
- BF16 SwiGLU experts: the dispatch output, the fused gate/up projection's output (
w13; backward reads it through theunbindthat splits it), the SiLU, the gate product and FC2's output. That's 5 per MoE layer, or 25 across the 5 MoE layers of the DSv3 debug model. - A fused MXFP8 expert MLP: everything it saves for backward (its FC1 output and its quantized FC1/FC2 inputs with their block scales), plus FC2's output. Backward there reads the quantized copy of the dispatch output, not the dispatch output itself, so that one isn't stashed.
Only what the stash can't hold keeps SAC's decision, e.g. the dispatch and combine collectives themselves, the per-row router scores and the expert weights.
|
|
||
| @custom_op("paged_stash::stash_", mutates_args=("handle",)) | ||
| def stash_( | ||
| handle: torch.Tensor, |
There was a problem hiding this comment.
maybe there is a good reason for this, but I wonder why you need to preallocate the handle tensor and inplace modify ?
can you just create the handle in this op and return?
There was a problem hiding this comment.
This would also save you an empty node.
There was a problem hiding this comment.
Good question. The mutation is what keeps the stash in GraphPP's forward callable.
GraphPP's partitioner saves for backward only what forward outputs depend on (_saved_values_for_backward) plus forward mutations (_forward_mutations_to_materialize). A stash that returns its handle is neither, since only backward's reload reads it. So the partitioner moves the stash into backward, and forward saves the full padded activation, the opposite of what we want.
test_graphpp_partition_keeps_stashes_in_forward_and_reloads_in_backward tests that.
There was a problem hiding this comment.
Also note the discussion here: #3216 (comment)
There was a problem hiding this comment.
tbh, I think this is a graphPP partitioner problem. it shouldn't move the forward nodes into backward subgraph.
but I will let this go.
| # last_use_of_storage only exists to pin an aliasing consumer before the | ||
| # wait; a consumer that would itself land after the wait cannot serve | ||
| # that role, so drop it rather than create a cycle. | ||
| last_use_arg = _find_last_tensor_consumer(info.last_fwd_consumer) | ||
| if last_use_arg is not None and last_use_arg is not wait_anchor: | ||
| if node_to_index.get(last_use_arg, -1) > node_to_index.get(wait_anchor, -1): | ||
| last_use_arg = None | ||
| wait_node = gm.graph.call_function( | ||
| paged_stash_ops.wait_stash_.default, | ||
| args=(handle, node, last_use_arg), | ||
| ) | ||
| wait_node.meta.update(src_meta) | ||
| wait_node.meta["val"] = None | ||
| wait_anchor.append(wait_node) |
There was a problem hiding this comment.
your profiler trace can tell better, but I guess you can just put wait_stash at the end of the layer to ensure overlap.
There was a problem hiding this comment.
Thanks. I checked this in profiles of the change (DSv3 debug model, 4x GB200, EP=2; CUDA graphs without PP, and GraphPP with PP=2 Interleaved1F1B).
The old wait_stash_ sat right after each activation's last forward use, which is usually the very next op, so the trace showed the next compute kernel held until the copy finished: 76% (BF16) and 81% (MXFP8) of stash-copy time ran with nothing else on the GPU.
So I decided to redo this (which was based on the old cpu offload pass approach) and tried to match Megatron's paged stash scheduling now:
- A layer's stashes launch together once its expert MLP has produced everything it saves, as Megatron's
paged_stash_group_commitdoes, so no copy competes with the expert GEMMs. - They are joined, and the padded activations freed, at the next MoE layer's group start:
paged_stash.group_starton the dispatch output, just before the expert MLP reads it (Megatron'spaged_stash_group_start/wait_for_stash_to_complete), or at a backward's firstreload, whichever comes first. The manager holds the activations until then, so under GraphPP the join can fall in the next pipeline action, as in Megatron.
wait_stash_ is gone. The stash is still the forward mutation of the handle that keeps it in GraphPP's forward callable.
Stash-copy time with no other kernel on the GPU is now 60 us/step in BF16 (was 692) and 3.5 us in MXFP8 (was 499). The MoE layer's forward is about 100 us shorter, and loss and grad_norm are identical in all four configs. Memory: in the allocator history of the step CUDA graphs capture, each layer's padded activations are freed inside the next layer's group_start. At most one layer's set is alive at a time, plus in BF16 the next layer's dispatch output until that join. The graph's live peak is unchanged.
Overlap still isn't guaranteed: the copy kernel launches 2048 CTAs (Megatron's cap) and fills every SM, so compute that needs the whole GPU waits for SMs. Giving the copy a smaller SM footprint would be a separate tuning change.
| return erased | ||
|
|
||
|
|
||
| def _prefetch_reloads(gm: torch.fx.GraphModule, n_layers: int) -> int: |
There was a problem hiding this comment.
I wonder how prefetch reload works in the case of PP?
Is the prefetch always limited to be within the stage? Do you see need to prefetch earlier for better overlap?
There was a problem hiding this comment.
It was limited to the stage until now: the pass moved each reload one backward layer earlier inside the same graph, so a stage's first paged layer was only reloaded at the start of its own backward action.
It now prefetches the way Megatron does, one schedule entry ahead and across pipeline actions:
- The manager builds each rank's schedule of paged-layer forwards and backwards from the GraphPP actions (
GraphRuntime.pipeline_liveness_schedule, which keeps PyTorch's action types). That's the list Megatron records as_pp_schedule, MoE layers only. - A forward's group commit (its last stash) issues the reloads of the next entry when that entry is a backward. On rank 0 of the PP=2 run, for example,
2F1reloads2B0's first layer, across the dense0F2action in between. paged_stash.reload_nextsits on the gradient of the dispatch output, right after the expert MLP backward produces it (Megatron'sPipelinePreScheduleFunction.backward). It issues the next entry's reloads: the next layer of the same backward, or the first layer of the next backward on the rank (2B0->2B1;3B3->1B2, across stages).reloadhands backward the prefetched tensor. The same schedule now also decides skip-on-immediate-backward.
Prefetch across actions (from rank0 trace) - 2F1's 10 copies end at 927.53, then 5 pops run 927.54–927.67. They finish before PP:2BACKWARD0 starts at 929.69, with PP:0F2 in between.



Prefetch across stages (from rank2 trace) - 5 pops at 1123.45–1123.60, issued inside PP:3BACKWARD3, before PP:1BACKWARD2 starts at 1127.46.
Skip paging when backward is immediate (from rank2 trace) - the paged_stash::stash_ and reload CPU ops are there, but stream 67 has no copy or pop kernels.


Attaching the profiles:
rank0_trace.json.gz
rank1_trace.json.gz
rank2_trace.json.gz
rank3_trace.json.gz
SherlockNoMad
left a comment
There was a problem hiding this comment.
Overall lgtm with minor comments.
…shing" Paged stash SAC for MoE expert activations: pre-allocated paged buffers store dynamic-shaped _grouped_mm outputs for the backward pass, avoiding both recomputation cost and memory fragmentation from variable token counts. - Joint-graph pass (paged_stash_graph_pass.py): inserts paged_stash.copy/pop ops using ao's stream infrastructure, redirecting backward consumers through paged buffers so SAC+remat naturally ignores stashed activations. - PagedStashTrainer (train.py): extends GraphTrainer with 3-level overflow defense (host spillover, cross-rank detection, retry with buffer growth). - Memory policy registration: paged_stash and paged_stash_save_only policies. - Fine-grained annotation via annotate_fn on _run_experts_grouped_mm. - Comparison with Megatron's implementation here: https://gist.github.com/syed-ahmed/f82d8485007eef91e90f08f24607d940 AI assistant used: Claude Opus 4.7 (1M context) <noreplyanthropic.com> [ghstack-poisoned]
…shing" Paged stash SAC for MoE expert activations: pre-allocated paged buffers store dynamic-shaped _grouped_mm outputs for the backward pass, avoiding both recomputation cost and memory fragmentation from variable token counts. - Joint-graph pass (paged_stash_graph_pass.py): inserts paged_stash.copy/pop ops using ao's stream infrastructure, redirecting backward consumers through paged buffers so SAC+remat naturally ignores stashed activations. - PagedStashTrainer (train.py): extends GraphTrainer with 3-level overflow defense (host spillover, cross-rank detection, retry with buffer growth). - Memory policy registration: paged_stash and paged_stash_save_only policies. - Fine-grained annotation via annotate_fn on _run_experts_grouped_mm. - Comparison with Megatron's implementation here: https://gist.github.com/syed-ahmed/f82d8485007eef91e90f08f24607d940 AI assistant used: Claude Opus 4.7 (1M context) <noreplyanthropic.com> [ghstack-poisoned]
…shing" Paged stash SAC for MoE expert activations: pre-allocated paged buffers store dynamic-shaped _grouped_mm outputs for the backward pass, avoiding both recomputation cost and memory fragmentation from variable token counts. - Joint-graph pass (paged_stash_graph_pass.py): inserts paged_stash.copy/pop ops using ao's stream infrastructure, redirecting backward consumers through paged buffers so SAC+remat naturally ignores stashed activations. - PagedStashTrainer (train.py): extends GraphTrainer with 3-level overflow defense (host spillover, cross-rank detection, retry with buffer growth). - Memory policy registration: paged_stash and paged_stash_save_only policies. - Fine-grained annotation via annotate_fn on _run_experts_grouped_mm. - Comparison with Megatron's implementation here: https://gist.github.com/syed-ahmed/f82d8485007eef91e90f08f24607d940 AI assistant used: Claude Opus 4.7 (1M context) <noreplyanthropic.com> [ghstack-poisoned]
|
This looks good to me. Still need @tianyu-l stamp for merge. |
|
Failing test is not related to this PR. Going ahead and merging. |
Stack from [ghstack](https://github.com/ezyang/ghstack) (oldest at bottom): * __->__ #3218 * #3217 * #3216
Stack from ghstack (oldest at bottom):
Paged stash SAC for MoE expert activations: pre-allocated paged buffers
store dynamic-shaped _grouped_mm outputs for the backward pass, avoiding
both recomputation cost and memory fragmentation from variable token counts.
ops using ao's stream infrastructure, redirecting backward consumers through
paged buffers so SAC+remat naturally ignores stashed activations.
defense (host spillover, cross-rank detection, retry with buffer growth).
AI assistant used: Claude Opus 4.7 (1M context) [email protected]