Skip to content

fix(dynamo): write copy-back buffers when the compiled module runs in PyTorch - #5095

Draft
shoumikhin wants to merge 2 commits into
pytorch:mainfrom
shoumikhin:copyback-writeback
Draft

shoumikhin wants to merge 2 commits into
pytorch:mainfrom
shoumikhin:copyback-writeback

Conversation

@shoumikhin

@shoumikhin shoumikhin commented Nov 22, 2026 •

Copy link
Copy Markdown
Contributor

A model can update a buffer in forward, as in self.state.add_(x). When the engine cannot do that in place, compile returns the new value as an extra graph output ("copy-back") for ExecuTorch to write. Called from PyTorch, the compiled module dropped that value, so the next call read the old buffer. Refit lost the buffer's state, and a TorchScript save or a save after pickling froze it.

1. Refit output check. refit_module_weights(verify_output=True) reported success without comparing anything when the two results had different container types, such as a tensor against a 1-tuple. Both modules also read the same input tensors. Now both results are compared leaf by leaf, and any difference in count, value, size, type or dtype returns False. Each module gets its own copy of the inputs, and inputs that share memory still share it.

2. Write-back. The generated forward copies each copy-back value into its buffer before it returns, without autograd history. The values stay graph outputs, so saving as an ExportedProgram, for AOT Inductor or for ExecuTorch declares them as buffer mutations. A plain non-strict torch.export.export of the compiled module still returns them as extra outputs.

  • Clones stay. Lowering erased a clone of the buffer, so old = buf.clone(); buf.copy_(x); return old returned the overwritten buffer.
  • Read before write. A value that can share memory with a buffer, such as a view of its own, is copied before the write.
  • Pickling. torch.load rebuilds forward by tracing it, which records the writes as graph nodes, so the loaded module keeps writing its buffers. A written value that depends on no input or buffer, as from torch.rand, cannot be traced, so torch.load raises.
  • Checks leave the state alone. A TorchScript save of a module that writes buffers, and verify_output, put back each dense buffer they changed.
  • Refit lifts written buffers as compile does and keeps the state the module reached.
  • Full compilation. With require_full_compilation, written buffers stay around the one engine. On main this failed.
  • Names. Nested buffers get unique flat names.

Tested on Linux x86_64, A100, TensorRT 11.4, torch 2.16 nightly: tests/py/dynamo/lowering/test_buffer_lifting.py passes, except the TorchScript save test, skipped since this nightly has no torch.jit.trace. Each new test fails with its fix removed. tests/py/dynamo/models/test_model_refit.py gives the same results as on main. CI does not run these tests until the TorchScript removal in the nightly is handled (#5059).

@meta-cla meta-cla Bot added the cla signed label Nov 22, 2026
@github-actions github-actions Bot added component: tests Issues re: Tests component: lowering Issues re: The lowering / preprocessing passes component: core Issues re: The core compiler component: api [Python] Issues re: Python API component: dynamo Issues relating to the `torch.compile` or `torch._dynamo.export` paths labels Nov 22, 2026
@shoumikhin
shoumikhin force-pushed the copyback-writeback branch 6 times, most recently from f9a7627 to 78279ac Compare November 23, 2026 19:55
… own inputs

refit_module_weights(verify_output=True) runs the refitted module and the
new model on the same inputs and compares what they return. Two things made
that check wrong:

- When the two results had different container types, for example a tensor
  against a 1-tuple, it logged a warning and reported success without
  comparing anything. A compiled module can return a tuple where the model
  returns one tensor or a dictionary.
- Both modules read the same input tensors. A model that writes an input in
  place changed what the other module then read, and changed the caller's
  tensors.

The check now flattens both results and compares them leaf by leaf.
Dictionary keys must match where both sides have them, also the keys of an
entry that holds no tensor. A different number of leaves, value, size, type
or dtype fails the check, which returns False instead of raising. Each
module gets its own copy of the inputs. Inputs that share memory, including
conjugate and negative views and a DLPack view inside another input's
memory, still share it in the copies, so a module that skips a write into
one of them fails the check.

The new output check tests fail without this change: an int against a tensor
and a float32 against a float16 output raised, and a missed write into an
input shared through a view was accepted.

Signed-off-by: Anthony Shoumikhin <[email protected]>
… PyTorch

A model can update a buffer in forward, as in self.state.add_(x). When the
engine cannot update it in place, compile returns its new value as an extra
graph output ("copy-back") for ExecuTorch to write. Called from PyTorch, the
compiled module dropped that value, so the next call read the old buffer.
Refit lost the buffer's state, and a TorchScript save or a save after
pickling froze it.

The generated forward now copies each copy-back value into its buffer before
it returns, without autograd history. The values stay graph outputs, so
saving as an ExportedProgram, for AOT Inductor or for ExecuTorch declares
them as buffer mutations. A plain non-strict torch.export.export of the
compiled module still returns them as extra outputs.

- Clones stay. Lowering erased a clone of the buffer, so old = buf.clone();
  buf.copy_(x); return old returned the overwritten buffer.
- Read before write. A value that can share memory with a buffer, such as a
  view of its own (self.state = self.state.t()), is copied first, and so is
  a returned view of a buffer given other contents. A saved ExportedProgram
  still lacks that copy, as on main.
- Pickling. torch.load rebuilds forward by tracing it, which records the
  writes as aten.copy_ nodes, so the loaded module writes its buffers, refit
  keeps the writes, and an export of it declares them. A written value that
  depends on no input or buffer, as from torch.rand, cannot be traced, so
  torch.load raises.
- Checks leave the state alone. A TorchScript save of a module that writes
  buffers, also after pickling, and refit's verify_output, put back each
  strided buffer they changed.
- Refit lifts written buffers as compile does and keeps the state the module
  reached. Like compile, a graph that fully converts under
  require_full_compilation keeps its engine at any size. verify_output
  compares with the new model as exported.
- Full compilation. With require_full_compilation, written buffers stay
  around the one engine. On main this failed, even for a write the engine
  does in place.
- Names. Nested buffers get free flattened names.

Tests cover an accumulating model, a returned clone, saved and loaded,
buffers read through a view of themselves or made in PyTorch, inputs named
like built-ins, colliding nested names, putting back buffers, a TorchScript
save, a pickled module, its refit and a write it cannot rebuild, an AOT
Inductor package, full compilation, refit with new weights and with nothing
to convert, and a write-back that gives a cache no gradient history.

Signed-off-by: Anthony Shoumikhin <[email protected]>
@shoumikhin
shoumikhin marked this pull request as draft November 23, 2026 21:54

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

cla signed component: api [Python] Issues re: Python API component: core Issues re: The core compiler component: dynamo Issues relating to the `torch.compile` or `torch._dynamo.export` paths component: lowering Issues re: The lowering / preprocessing passes component: tests Issues re: Tests

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant