Skip to content

External remat.op redesign — single-tape SAVE/RECOMPUTE, drop native_op and pytree (#2) - #2

Closed
ezyang wants to merge 1 commit into
meta-pytorch:mainfrom
ezyang:export-D110330840
Closed

ezyang wants to merge 1 commit into
meta-pytorch:mainfrom
ezyang:export-D110330840

Conversation

@ezyang

@ezyang ezyang commented Jul 2, 2026 •

Copy link
Copy Markdown
Contributor

Summary:

Human summary

This diff does a major redesign and rewrite of torch_remat, where all of the heavy lifting is done by remat.op rather than auto_forward (which is now completely deleted). However, it is probably best to review this not as a diff, but just as a completely new torch_remat implementation from the ground up, because as I was doing review I ended up having to do a bunch of other cleanups (seen in the AI summary below), and I also fixed some feature requests (for example, not redundantly re-saving saved for backwards inputs that come from recompute regions). I also reorganized the module structure so that the files are smaller and easier to tackle in a modular way.

AI generated summary

Reworks torch_remat so activation save/recompute is driven entirely from the call site by remat.op, with the wrapped callable used unmodified. Removes the in-forward handle protocol (get_handle, RematHandle, maybe_load_saved, save_or_load_inputs, named save_for_backward, record_outputs), the auto_forward decorator, and native_op with its selective-activation-checkpointing (SAC) path. A single tape mechanism now handles custom autograd.Functions, native ops, and multi-op spans with no per-op rewrite.

Design (Option A): a SAVE op installs a nested saved_tensors_hooks around the call so the tensors its autograd nodes save stay as ordinary autograd saved tensors on the original forward graph — owned by autograd, present at backward with zero recompute, and freed by autograd afterward. The original grad_fn unpacks them at backward, so the op is never recomputed and is skipped (returning data-inaccessible placeholder outputs) during recompute. A RECOMPUTE op reruns and ferries any upstream SAVE output it consumes through the tape, fabricating a non-leaf requires-grad stand-in so the rerun rebuilds its backward node and checkpoint's saved-tensor count stays aligned.

Saved inputs are ferried rather than retained: when a SAVE op saves one of its own inputs — or a view of one — that value is not pinned on the autograd graph. A RECOMPUTE-sourced (or region) input is reproduced during replay and captured detached; a SAVE-sourced input is stored in the original forward via a tape slot; a saved view is rebuilt from the reproduced base with as_strided. Saved-input detection matches by storage identity (not Python object identity), which both enables view ferrying and fixes a latent bug where autograd can hand the pack hook a different Tensor object wrapping the same TensorImpl. Cases that cannot be safely reconstructed (disjoint views, dtype reinterprets, non-contiguous or stub bases) fall back to being kept resident, so correctness never depends on the classification, and a recompute-time guard raises if a ferried view's base reproduces with a different layout.

In-place guard: autograd's native version-counter guard does NOT fire for tensors packed through custom saved_tensors_hooks (verified empirically — backward silently computes a wrong gradient), so the identity unpack hook records each tensor's _version at pack and re-checks it at backward, raising the same modified in-place error.

Also splits the monolithic _api.py into small single-responsibility private modules with an acyclic dependency graph, leaving _api.py as the user-facing surface (checkpoint, op, save_for_backward, saved_tensors_hooks, CheckpointPolicy):

  • _placeholder.py — the storage-free _PlaceholderTensor wrapper subclass and its helpers; depends only on torch.
  • _trace.py — the diagnostic tracing surface (OpTrace / ScopeTrace / RematTrace, collect_trace, trace_scope).
  • _region.py — checkpoint-region and phase plumbing (_Phase, is_recomputing, region state/context), subsuming the former _state.py.

The dependency graph is acyclic: _placeholder and _region are leaves; _trace -> _region; _api -> {_placeholder, _region, _trace}; _reporting -> {_api, _placeholder, _region}. The public API is unchanged; __init__.py re-exports each symbol from its new home.

Finally drops the torch.utils._pytree dependency in favor of a dedicated _pytree.py module handling exactly what the library routes: a leaf, or a single hop of nesting (list / tuple / dict of leaves, as torch.cat([a, b], dim=0) takes), with deeper nesting rejected early rather than silently traversed, and no persisted treespec (recompute re-receives the live args/kwargs, so structure is only ever walked or mapped-and-rebuilt in place). Expanding one hop matters for correctness — a stub SAVE output nested inside a container must keep a stable leaf index so it is ferried during recompute rather than blowing up as a placeholder. Ferried RECOMPUTE inputs are keyed by the argument path they arrived through (args[0], args[1][0], kwargs["foo"]) instead of a flat index, so memory reports and ferry errors point at where the input came from.

This is the eager implementation only. torch.compile support is intentionally out of scope here and will land as a separate change. genai/llama4x/projects/experimental/remat_example/ is left for a follow-up conversion.

Differential Revision: D110330840

@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Jul 2, 2026
@meta-codesync

meta-codesync Bot commented Jul 2, 2026

Copy link
Copy Markdown

@ezyang has exported this pull request. If you are a Meta employee, you can view the originating Diff in D110330840.

@meta-codesync meta-codesync Bot changed the title External remat.op redesign — single-tape SAVE/RECOMPUTE, drop native_op and pytree External remat.op redesign — single-tape SAVE/RECOMPUTE, drop native_op and pytree (#2) Jul 5, 2026
ezyang added a commit to ezyang/remat that referenced this pull request Jul 5, 2026
…op and pytree (meta-pytorch#2)

Summary:

# Human summary

This diff does a major redesign and rewrite of torch_remat, where all of the heavy lifting is done by remat.op rather than auto_forward (which is now completely deleted). However, it is probably best to review this not as a diff, but just as a completely new `torch_remat` implementation from the ground up, because as I was doing review I ended up having to do a bunch of other cleanups (seen in the AI summary below), and I also fixed some feature requests (for example, not redundantly re-saving saved for backwards inputs that come from recompute regions). I also reorganized the module structure so that the files are smaller and easier to tackle in a modular way.

# AI generated summary

Reworks `torch_remat` so activation save/recompute is driven entirely from the call site by `remat.op`, with the wrapped callable used unmodified. Removes the in-`forward` handle protocol (`get_handle`, `RematHandle`, `maybe_load_saved`, `save_or_load_inputs`, named `save_for_backward`, `record_outputs`), the `auto_forward` decorator, and `native_op` with its selective-activation-checkpointing (SAC) path. A single tape mechanism now handles custom `autograd.Function`s, native ops, and multi-op spans with no per-op rewrite.

Design (Option A): a `SAVE` op installs a nested `saved_tensors_hooks` around the call so the tensors its autograd nodes save stay as ordinary autograd saved tensors on the original forward graph — owned by autograd, present at backward with zero recompute, and freed by autograd afterward. The original grad_fn unpacks them at backward, so the op is never recomputed and is skipped (returning data-inaccessible placeholder outputs) during recompute. A `RECOMPUTE` op reruns and ferries any upstream `SAVE` output it consumes through the tape, fabricating a non-leaf requires-grad stand-in so the rerun rebuilds its backward node and checkpoint's saved-tensor count stays aligned.

Saved inputs are ferried rather than retained: when a `SAVE` op saves one of its own inputs — or a view of one — that value is not pinned on the autograd graph. A RECOMPUTE-sourced (or region) input is reproduced during replay and captured detached; a SAVE-sourced input is stored in the original forward via a tape slot; a saved view is rebuilt from the reproduced base with `as_strided`. Saved-input detection matches by storage identity (not Python object identity), which both enables view ferrying and fixes a latent bug where autograd can hand the pack hook a different `Tensor` object wrapping the same `TensorImpl`. Cases that cannot be safely reconstructed (disjoint views, dtype reinterprets, non-contiguous or stub bases) fall back to being kept resident, so correctness never depends on the classification, and a recompute-time guard raises if a ferried view's base reproduces with a different layout.

In-place guard: autograd's native version-counter guard does NOT fire for tensors packed through custom `saved_tensors_hooks` (verified empirically — backward silently computes a wrong gradient), so the identity unpack hook records each tensor's `_version` at pack and re-checks it at backward, raising the same `modified in-place` error.

Also splits the monolithic `_api.py` into small single-responsibility private modules with an acyclic dependency graph, leaving `_api.py` as the user-facing surface (`checkpoint`, `op`, `save_for_backward`, `saved_tensors_hooks`, `CheckpointPolicy`):
- `_placeholder.py` — the storage-free `_PlaceholderTensor` wrapper subclass and its helpers; depends only on `torch`.
- `_trace.py` — the diagnostic tracing surface (`OpTrace` / `ScopeTrace` / `RematTrace`, `collect_trace`, `trace_scope`).
- `_region.py` — checkpoint-region and phase plumbing (`_Phase`, `is_recomputing`, region state/context), subsuming the former `_state.py`.

The dependency graph is acyclic: `_placeholder` and `_region` are leaves; `_trace -> _region`; `_api -> {_placeholder, _region, _trace}`; `_reporting -> {_api, _placeholder, _region}`. The public API is unchanged; `__init__.py` re-exports each symbol from its new home.

Finally drops the `torch.utils._pytree` dependency in favor of a dedicated `_pytree.py` module handling exactly what the library routes: a leaf, or a single hop of nesting (`list` / `tuple` / `dict` of leaves, as `torch.cat([a, b], dim=0)` takes), with deeper nesting rejected early rather than silently traversed, and no persisted treespec (recompute re-receives the live `args`/`kwargs`, so structure is only ever walked or mapped-and-rebuilt in place). Expanding one hop matters for correctness — a stub `SAVE` output nested inside a container must keep a stable leaf index so it is ferried during recompute rather than blowing up as a placeholder. Ferried `RECOMPUTE` inputs are keyed by the argument path they arrived through (`args[0]`, `args[1][0]`, `kwargs["foo"]`) instead of a flat index, so memory reports and ferry errors point at where the input came from.

This is the eager implementation only. `torch.compile` support is intentionally out of scope here and will land as a separate change. `genai/llama4x/projects/experimental/remat_example/` is left for a follow-up conversion.

Differential Revision: D110330840
@ezyang
ezyang force-pushed the export-D110330840 branch from 1b249eb to facefec Compare July 5, 2026 03:55
ezyang added a commit to ezyang/remat that referenced this pull request Jul 5, 2026
…op and pytree (meta-pytorch#2)

Summary:

# Human summary

This diff does a major redesign and rewrite of torch_remat, where all of the heavy lifting is done by remat.op rather than auto_forward (which is now completely deleted). However, it is probably best to review this not as a diff, but just as a completely new `torch_remat` implementation from the ground up, because as I was doing review I ended up having to do a bunch of other cleanups (seen in the AI summary below), and I also fixed some feature requests (for example, not redundantly re-saving saved for backwards inputs that come from recompute regions). I also reorganized the module structure so that the files are smaller and easier to tackle in a modular way.

# AI generated summary

Reworks `torch_remat` so activation save/recompute is driven entirely from the call site by `remat.op`, with the wrapped callable used unmodified. Removes the in-`forward` handle protocol (`get_handle`, `RematHandle`, `maybe_load_saved`, `save_or_load_inputs`, named `save_for_backward`, `record_outputs`), the `auto_forward` decorator, and `native_op` with its selective-activation-checkpointing (SAC) path. A single tape mechanism now handles custom `autograd.Function`s, native ops, and multi-op spans with no per-op rewrite.

Design (Option A): a `SAVE` op installs a nested `saved_tensors_hooks` around the call so the tensors its autograd nodes save stay as ordinary autograd saved tensors on the original forward graph — owned by autograd, present at backward with zero recompute, and freed by autograd afterward. The original grad_fn unpacks them at backward, so the op is never recomputed and is skipped (returning data-inaccessible placeholder outputs) during recompute. A `RECOMPUTE` op reruns and ferries any upstream `SAVE` output it consumes through the tape, fabricating a non-leaf requires-grad stand-in so the rerun rebuilds its backward node and checkpoint's saved-tensor count stays aligned.

Saved inputs are ferried rather than retained: when a `SAVE` op saves one of its own inputs — or a view of one — that value is not pinned on the autograd graph. A RECOMPUTE-sourced (or region) input is reproduced during replay and captured detached; a SAVE-sourced input is stored in the original forward via a tape slot; a saved view is rebuilt from the reproduced base with `as_strided`. Saved-input detection matches by storage identity (not Python object identity), which both enables view ferrying and fixes a latent bug where autograd can hand the pack hook a different `Tensor` object wrapping the same `TensorImpl`. Cases that cannot be safely reconstructed (disjoint views, dtype reinterprets, non-contiguous or stub bases) fall back to being kept resident, so correctness never depends on the classification, and a recompute-time guard raises if a ferried view's base reproduces with a different layout.

In-place guard: autograd's native version-counter guard does NOT fire for tensors packed through custom `saved_tensors_hooks` (verified empirically — backward silently computes a wrong gradient), so the identity unpack hook records each tensor's `_version` at pack and re-checks it at backward, raising the same `modified in-place` error.

Also splits the monolithic `_api.py` into small single-responsibility private modules with an acyclic dependency graph, leaving `_api.py` as the user-facing surface (`checkpoint`, `op`, `save_for_backward`, `saved_tensors_hooks`, `CheckpointPolicy`):
- `_placeholder.py` — the storage-free `_PlaceholderTensor` wrapper subclass and its helpers; depends only on `torch`.
- `_trace.py` — the diagnostic tracing surface (`OpTrace` / `ScopeTrace` / `RematTrace`, `collect_trace`, `trace_scope`).
- `_region.py` — checkpoint-region and phase plumbing (`_Phase`, `is_recomputing`, region state/context), subsuming the former `_state.py`.

The dependency graph is acyclic: `_placeholder` and `_region` are leaves; `_trace -> _region`; `_api -> {_placeholder, _region, _trace}`; `_reporting -> {_api, _placeholder, _region}`. The public API is unchanged; `__init__.py` re-exports each symbol from its new home.

Finally drops the `torch.utils._pytree` dependency in favor of a dedicated `_pytree.py` module handling exactly what the library routes: a leaf, or a single hop of nesting (`list` / `tuple` / `dict` of leaves, as `torch.cat([a, b], dim=0)` takes), with deeper nesting rejected early rather than silently traversed, and no persisted treespec (recompute re-receives the live `args`/`kwargs`, so structure is only ever walked or mapped-and-rebuilt in place). Expanding one hop matters for correctness — a stub `SAVE` output nested inside a container must keep a stable leaf index so it is ferried during recompute rather than blowing up as a placeholder. Ferried `RECOMPUTE` inputs are keyed by the argument path they arrived through (`args[0]`, `args[1][0]`, `kwargs["foo"]`) instead of a flat index, so memory reports and ferry errors point at where the input came from.

This is the eager implementation only. `torch.compile` support is intentionally out of scope here and will land as a separate change. `genai/llama4x/projects/experimental/remat_example/` is left for a follow-up conversion.

Differential Revision: D110330840
@ezyang
ezyang force-pushed the export-D110330840 branch from facefec to 48cb9f6 Compare July 5, 2026 13:31
ezyang added a commit to ezyang/remat that referenced this pull request Jul 5, 2026
…op and pytree (meta-pytorch#2)

Summary:
Pull Request resolved: meta-pytorch#2

# Human summary

This diff does a major redesign and rewrite of torch_remat, where all of the heavy lifting is done by remat.op rather than auto_forward (which is now completely deleted). However, it is probably best to review this not as a diff, but just as a completely new `torch_remat` implementation from the ground up, because as I was doing review I ended up having to do a bunch of other cleanups (seen in the AI summary below), and I also fixed some feature requests (for example, not redundantly re-saving saved for backwards inputs that come from recompute regions). I also reorganized the module structure so that the files are smaller and easier to tackle in a modular way.

# AI generated summary

Reworks `torch_remat` so activation save/recompute is driven entirely from the call site by `remat.op`, with the wrapped callable used unmodified. Removes the in-`forward` handle protocol (`get_handle`, `RematHandle`, `maybe_load_saved`, `save_or_load_inputs`, named `save_for_backward`, `record_outputs`), the `auto_forward` decorator, and `native_op` with its selective-activation-checkpointing (SAC) path. A single tape mechanism now handles custom `autograd.Function`s, native ops, and multi-op spans with no per-op rewrite.

Design (Option A): a `SAVE` op installs a nested `saved_tensors_hooks` around the call so the tensors its autograd nodes save stay as ordinary autograd saved tensors on the original forward graph — owned by autograd, present at backward with zero recompute, and freed by autograd afterward. The original grad_fn unpacks them at backward, so the op is never recomputed and is skipped (returning data-inaccessible placeholder outputs) during recompute. A `RECOMPUTE` op reruns and ferries any upstream `SAVE` output it consumes through the tape, fabricating a non-leaf requires-grad stand-in so the rerun rebuilds its backward node and checkpoint's saved-tensor count stays aligned.

Saved inputs are ferried rather than retained: when a `SAVE` op saves one of its own inputs — or a view of one — that value is not pinned on the autograd graph. A RECOMPUTE-sourced (or region) input is reproduced during replay and captured detached; a SAVE-sourced input is stored in the original forward via a tape slot; a saved view is rebuilt from the reproduced base with `as_strided`. Saved-input detection matches by storage identity (not Python object identity), which both enables view ferrying and fixes a latent bug where autograd can hand the pack hook a different `Tensor` object wrapping the same `TensorImpl`. Cases that cannot be safely reconstructed (disjoint views, dtype reinterprets, non-contiguous or stub bases) fall back to being kept resident, so correctness never depends on the classification, and a recompute-time guard raises if a ferried view's base reproduces with a different layout.

In-place guard: autograd's native version-counter guard does NOT fire for tensors packed through custom `saved_tensors_hooks` (verified empirically — backward silently computes a wrong gradient), so the identity unpack hook records each tensor's `_version` at pack and re-checks it at backward, raising the same `modified in-place` error.

Also splits the monolithic `_api.py` into small single-responsibility private modules with an acyclic dependency graph, leaving `_api.py` as the user-facing surface (`checkpoint`, `op`, `save_for_backward`, `saved_tensors_hooks`, `CheckpointPolicy`):
- `_placeholder.py` — the storage-free `_PlaceholderTensor` wrapper subclass and its helpers; depends only on `torch`.
- `_trace.py` — the diagnostic tracing surface (`OpTrace` / `ScopeTrace` / `RematTrace`, `collect_trace`, `trace_scope`).
- `_region.py` — checkpoint-region and phase plumbing (`_Phase`, `is_recomputing`, region state/context), subsuming the former `_state.py`.

The dependency graph is acyclic: `_placeholder` and `_region` are leaves; `_trace -> _region`; `_api -> {_placeholder, _region, _trace}`; `_reporting -> {_api, _placeholder, _region}`. The public API is unchanged; `__init__.py` re-exports each symbol from its new home.

Finally drops the `torch.utils._pytree` dependency in favor of a dedicated `_pytree.py` module handling exactly what the library routes: a leaf, or a single hop of nesting (`list` / `tuple` / `dict` of leaves, as `torch.cat([a, b], dim=0)` takes), with deeper nesting rejected early rather than silently traversed, and no persisted treespec (recompute re-receives the live `args`/`kwargs`, so structure is only ever walked or mapped-and-rebuilt in place). Expanding one hop matters for correctness — a stub `SAVE` output nested inside a container must keep a stable leaf index so it is ferried during recompute rather than blowing up as a placeholder. Ferried `RECOMPUTE` inputs are keyed by the argument path they arrived through (`args[0]`, `args[1][0]`, `kwargs["foo"]`) instead of a flat index, so memory reports and ferry errors point at where the input came from.

This is the eager implementation only. `torch.compile` support is intentionally out of scope here and will land as a separate change. `genai/llama4x/projects/experimental/remat_example/` is left for a follow-up conversion.

Differential Revision: D110330840
@ezyang
ezyang force-pushed the export-D110330840 branch from 48cb9f6 to c6a9e4e Compare July 5, 2026 20:08
…op and pytree (meta-pytorch#2)

Summary:
Pull Request resolved: meta-pytorch#2

# Human summary

This diff does a major redesign and rewrite of torch_remat, where all of the heavy lifting is done by remat.op rather than auto_forward (which is now completely deleted). However, it is probably best to review this not as a diff, but just as a completely new `torch_remat` implementation from the ground up, because as I was doing review I ended up having to do a bunch of other cleanups (seen in the AI summary below), and I also fixed some feature requests (for example, not redundantly re-saving saved for backwards inputs that come from recompute regions). I also reorganized the module structure so that the files are smaller and easier to tackle in a modular way.

# AI generated summary

Reworks `torch_remat` so activation save/recompute is driven entirely from the call site by `remat.op`, with the wrapped callable used unmodified. Removes the in-`forward` handle protocol (`get_handle`, `RematHandle`, `maybe_load_saved`, `save_or_load_inputs`, named `save_for_backward`, `record_outputs`), the `auto_forward` decorator, and `native_op` with its selective-activation-checkpointing (SAC) path. A single tape mechanism now handles custom `autograd.Function`s, native ops, and multi-op spans with no per-op rewrite.

Design (Option A): a `SAVE` op installs a nested `saved_tensors_hooks` around the call so the tensors its autograd nodes save stay as ordinary autograd saved tensors on the original forward graph — owned by autograd, present at backward with zero recompute, and freed by autograd afterward. The original grad_fn unpacks them at backward, so the op is never recomputed and is skipped (returning data-inaccessible placeholder outputs) during recompute. A `RECOMPUTE` op reruns and ferries any upstream `SAVE` output it consumes through the tape, fabricating a non-leaf requires-grad stand-in so the rerun rebuilds its backward node and checkpoint's saved-tensor count stays aligned.

Saved inputs are ferried rather than retained: when a `SAVE` op saves one of its own inputs — or a view of one — that value is not pinned on the autograd graph. A RECOMPUTE-sourced (or region) input is reproduced during replay and captured detached; a SAVE-sourced input is stored in the original forward via a tape slot; a saved view is rebuilt from the reproduced base with `as_strided`. Saved-input detection matches by storage identity (not Python object identity), which both enables view ferrying and fixes a latent bug where autograd can hand the pack hook a different `Tensor` object wrapping the same `TensorImpl`. Cases that cannot be safely reconstructed (disjoint views, dtype reinterprets, non-contiguous or stub bases) fall back to being kept resident, so correctness never depends on the classification, and a recompute-time guard raises if a ferried view's base reproduces with a different layout.

In-place guard: autograd's native version-counter guard does NOT fire for tensors packed through custom `saved_tensors_hooks` (verified empirically — backward silently computes a wrong gradient), so the identity unpack hook records each tensor's `_version` at pack and re-checks it at backward, raising the same `modified in-place` error.

Also splits the monolithic `_api.py` into small single-responsibility private modules with an acyclic dependency graph, leaving `_api.py` as the user-facing surface (`checkpoint`, `op`, `save_for_backward`, `saved_tensors_hooks`, `CheckpointPolicy`):
- `_placeholder.py` — the storage-free `_PlaceholderTensor` wrapper subclass and its helpers; depends only on `torch`.
- `_trace.py` — the diagnostic tracing surface (`OpTrace` / `ScopeTrace` / `RematTrace`, `collect_trace`, `trace_scope`).
- `_region.py` — checkpoint-region and phase plumbing (`_Phase`, `is_recomputing`, region state/context), subsuming the former `_state.py`.

The dependency graph is acyclic: `_placeholder` and `_region` are leaves; `_trace -> _region`; `_api -> {_placeholder, _region, _trace}`; `_reporting -> {_api, _placeholder, _region}`. The public API is unchanged; `__init__.py` re-exports each symbol from its new home.

Finally drops the `torch.utils._pytree` dependency in favor of a dedicated `_pytree.py` module handling exactly what the library routes: a leaf, or a single hop of nesting (`list` / `tuple` / `dict` of leaves, as `torch.cat([a, b], dim=0)` takes), with deeper nesting rejected early rather than silently traversed, and no persisted treespec (recompute re-receives the live `args`/`kwargs`, so structure is only ever walked or mapped-and-rebuilt in place). Expanding one hop matters for correctness — a stub `SAVE` output nested inside a container must keep a stable leaf index so it is ferried during recompute rather than blowing up as a placeholder. Ferried `RECOMPUTE` inputs are keyed by the argument path they arrived through (`args[0]`, `args[1][0]`, `kwargs["foo"]`) instead of a flat index, so memory reports and ferry errors point at where the input came from.

This is the eager implementation only. `torch.compile` support is intentionally out of scope here and will land as a separate change. `genai/llama4x/projects/experimental/remat_example/` is left for a follow-up conversion.

Differential Revision: D110330840
@ezyang
ezyang force-pushed the export-D110330840 branch from c6a9e4e to fcfe55c Compare July 6, 2026 13:33
@meta-codesync meta-codesync Bot closed this in 4727cdb Jul 8, 2026
@meta-codesync meta-codesync Bot added the Merged label Jul 8, 2026
@meta-codesync

meta-codesync Bot commented Jul 8, 2026

Copy link
Copy Markdown

This pull request has been merged in 4727cdb.

tianyu-l added a commit to pytorch/torchtitan that referenced this pull request Nov 3, 2026
## Summary (human-written)
<!-- Write this yourself, not with an AI tool. 2-5 sentences: the
problem, why
     this approach, and what you checked yourself. -->

1. add proper remat support for HybridEP
2. add moe/README.md as a backend selection guidance

## Why
HybridEP dispatch and combine run outside torch_remat regions.
Consequently,
DefaultActivationRematConfig replays both during backward even though
its documented
policy retains EP communication. Users also lack a single guide
comparing the
supported EP execution paths and their graph, precision, and memory
constraints.

**Example.** One forward/backward through a routed-expert layer normally
needs
one dispatch and one combine in the forward, plus one call to each
primitive
for gradient computation. Activation remat can add another replay of the
forward communication pair:

| Policy | Extra communication before this PR | Extra communication
after this PR |
| --- | --- | --- |
| No remat | None | None |
| Default remat | 1 extra dispatch and 1 extra combine | None |
| Full remat | 1 extra dispatch and 1 extra combine | 1 extra dispatch
and 1 extra combine |

The default policy now retains the forward communication results for
expert
recomputation. Normal forward and gradient communication still run; full
remat
continues to replay communication as requested.

## What changed
- Declare HybridEP dispatch/combine regions controlled together by
`ep_communication`,
  matching DeepEP. Retain counts and scores consumed outside regions.
- Pass the forward handle through a CPU tensor ID because torch_remat
0.2.2 accepts
only tensor region outputs. Garbage collection releases cache entries. A
CPU
lookup op keeps autograd setup contexts traceable with FakeTensor/AOT.
Upstream
opaque-output support is tracked in [remat issue
#10](meta-pytorch/remat#10).
- Add an EP backend selection guide beside MoE, with configuration
examples,
remat semantics, capacity considerations, and links to public dependency
guides.
  No backend is removed or added.
- Mechanically share the existing DeepEP test harness with HybridEP,
then check
communication counts, exact loss/gradients, and graph capture. Run
HybridEP tests
  after its existing CI installer.

## Alternatives considered
- Retain the whole MoE call: would also retain expert compute that the
default
  policy intends to recompute.
- Return the existing opaque handle from the region: current torch_remat
rejects
it. The tensor-only contract comes from meta-pytorch/remat#2; upstream
opaque
  output support would allow removal of the tensor-ID cache.

## User-facing changes
| Before | After |
| --- | --- |
| HybridEP communication replays under default remat | Default/custom
saved policies retain it; full remat still replays it |
| Backend constraints scattered across recipes and implementation |
`torchtitan/models/common/moe/README.md` describes the available choices
|

## Numerics
No changes to routing, expert computation, checkpoint parameter names,
or precision.
Against main `ff96670a2`, DeepSeek V3 debug-model training with FSDP2 x
EP2 on two
GB300 GPUs produced bitwise-identical TensorBoard loss and grad_norm for
all 10
steps, with seed 42 and deterministic execution. Validation used
`scripts/loss_compare.py --steps 10 --no-seed-checkpoint --metrics
loss,grad_norm`,
exporting main's metrics and asserting equality on the branch with
`--import-result`.

## Testing
- `pre-commit run --all-files`: passed.
- Focused MoE, transform, and config-validation CPU tests: 73 passed.
The new
FakeTensor backward test catches host scalar reads in autograd setup
contexts.
- HybridEP GPU remat tests: 3 passed on two GB300 GPUs. Blocking and
nonblocking
dispatch both match no-remat loss/input/router/expert gradients exactly,
with
expected communication counts; saved communication also survives CUDA
graph replay.
- AOT-compiled FakeTensor dispatch/combine forward and backward: passed.
- HybridEP dependency for local GPU tests: public hybrid-ep commit
`4e890fd`.
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. Merged meta-exported

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant