Repository navigation
Conversation
|
@ezyang has exported this pull request. If you are a Meta employee, you can view the originating Diff in D110330840. |
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
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
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
…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
|
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`.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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_rematimplementation 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_rematso activation save/recompute is driven entirely from the call site byremat.op, with the wrapped callable used unmodified. Removes the in-forwardhandle protocol (get_handle,RematHandle,maybe_load_saved,save_or_load_inputs, namedsave_for_backward,record_outputs), theauto_forwarddecorator, andnative_opwith its selective-activation-checkpointing (SAC) path. A single tape mechanism now handles customautograd.Functions, native ops, and multi-op spans with no per-op rewrite.Design (Option A): a
SAVEop installs a nestedsaved_tensors_hooksaround 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. ARECOMPUTEop reruns and ferries any upstreamSAVEoutput 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
SAVEop 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 withas_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 differentTensorobject wrapping the sameTensorImpl. 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_versionat pack and re-checks it at backward, raising the samemodified in-placeerror.Also splits the monolithic
_api.pyinto small single-responsibility private modules with an acyclic dependency graph, leaving_api.pyas the user-facing surface (checkpoint,op,save_for_backward,saved_tensors_hooks,CheckpointPolicy):_placeholder.py— the storage-free_PlaceholderTensorwrapper subclass and its helpers; depends only ontorch._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:
_placeholderand_regionare leaves;_trace -> _region;_api -> {_placeholder, _region, _trace};_reporting -> {_api, _placeholder, _region}. The public API is unchanged;__init__.pyre-exports each symbol from its new home.Finally drops the
torch.utils._pytreedependency in favor of a dedicated_pytree.pymodule handling exactly what the library routes: a leaf, or a single hop of nesting (list/tuple/dictof leaves, astorch.cat([a, b], dim=0)takes), with deeper nesting rejected early rather than silently traversed, and no persisted treespec (recompute re-receives the liveargs/kwargs, so structure is only ever walked or mapped-and-rebuilt in place). Expanding one hop matters for correctness — a stubSAVEoutput nested inside a container must keep a stable leaf index so it is ferried during recompute rather than blowing up as a placeholder. FerriedRECOMPUTEinputs 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.compilesupport 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