Skip to content

fix(dynamo): cache writes reach caller tensors - #5096

Draft
shoumikhin wants to merge 4 commits into
pytorch:mainfrom
shoumikhin:kv-caller-tensor-writes
Draft

shoumikhin wants to merge 4 commits into
pytorch:mainfrom
shoumikhin:kv-caller-tensor-writes

Conversation

@shoumikhin

@shoumikhin shoumikhin commented Nov 22, 2026 •

Copy link
Copy Markdown
Contributor

This builds on #5095. Only the last 2 commits are new here.

A decoder can keep its KV cache in a caller's tensor:

def forward(self, cache, x, pos):
    cache.index_copy_(2, pos, x)
    return cache.sum(2)

Compiled, it differs from eager:

  • The converters update any eligible write into an input in place, so a
    functional torch.index_copy(cache, ...) changes the caller's tensor.
  • A write the KV cache layer cannot take (rank 3, strided, float64) is
    lost everywhere.
  • torch.compile's fallback writes into a clone lowering added.

The first commit fixes lowering on current PyTorch nightlies, where these
compiles failed with "'dict' object has no attribute 'discard'".

The second commit:

  • Only marked writes update in place. Buffer lifting marks a write
    _trt_kv_alias when an engine can apply it, and the index_copy and
    slice_scatter converters take only marked writes.
  • Caller tensors. A write is done in place only when it is one
    eligible write into a contiguous, non-float64 GPU tensor, read again
    later, and nothing reads its old contents. Otherwise its write-back
    copy_ stays, also for other writes such as x.add_(1), and readers of the old contents read a copy taken before
    it. A write predicted in place that still runs in PyTorch gets the copy_
    back. Write-backs run without autograd, as a model's own write under
    torch.no_grad() does. Every entry point does this.
  • Buffers keep main's rule, except that a buffer the engine gets a
    copy of, such as a float64 one under truncate_double, is copied back.
  • The serialized engine and require_full_compilation refuse a write into
    an input they cannot do in place. Main dropped the write.

Not covered, as on main: torch_tensorrt.compile loses a write into an
nn.Parameter. Saving a module
that keeps a write-back needs retrace=True; otherwise torch.export's
verifier rejects the kept copy_.

Tests compare with eager. They fail without this change for: a functional
write of an input, caller writes not done in place, add_ and copy_ into a
caller's tensor, the example at the
default min_block_size, a write next to an engine, a write under no_grad
into a tensor that needs a gradient, readers of the old contents, a
strided cache and its refit, float64 caches and buffers, torch.compile,
full compilation, the serialized engine, a saved module, the Windows cross
compile and the cache key. The new lowering test fails without the first
commit on such a nightly.

@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: conversion Issues re: Conversion stage component: core Issues re: The core compiler component: converters Issues re: Specific op converters component: api [Python] Issues re: Python API component: dynamo Issues relating to the `torch.compile` or `torch._dynamo.export` paths component: torch_compile labels Nov 22, 2026
@github-actions
github-actions Bot requested a review from narendasan November 22, 2026 02:19
@shoumikhin
shoumikhin force-pushed the kv-caller-tensor-writes branch 7 times, most recently from 89cef61 to 57d4dad 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]>
… node

The lowering passes use a FakeTensorUpdater that marks each node without a
fake value as not processed yet, so propagation fills the value in. Current
PyTorch nightlies keep the processed hashes in a dict keyed by node, not in a
set of hashes, so that step raised:

    AttributeError: 'dict' object has no attribute 'discard'

Any compile whose graph has such a node failed, for example a model that
writes into a caller's tensor in place. The updater now handles both forms.

The new test fails without this change on a nightly with the dict form. It
passes with and without the change on the older set form.

Signed-off-by: Anthony Shoumikhin <[email protected]>
A decoder can keep its KV cache in a caller's tensor:

    def forward(self, cache, x, pos):
        cache.index_copy_(2, pos, x)
        return cache.sum(2)

Compiled, it differs from eager:

- The converters update any eligible write into an input in place, so a
  functional torch.index_copy(cache, ...) changes the caller's tensor.
- A write the KV cache layer cannot take (rank 3, strided, float64) is lost
  everywhere.
- torch.compile's fallback writes into a clone lowering added.

- **Only marked writes update in place.** Buffer lifting marks a write
  _trt_kv_alias when an engine can apply it, and the index_copy and
  slice_scatter converters take only marked writes. The engine cache key
  records the mark and the input it names, so main's engines are not reused.
- **Caller tensors.** A write is done in place only when it is one eligible
  write into a contiguous, non-float64 GPU tensor, read again later, and
  nothing reads its old contents. Otherwise its write-back copy_ stays, also
  for other writes such as x.add_(1) but not a plugin's, and readers of the
  old contents read a copy taken before it. Cleanup, saving, refit and
  float32 truncation keep that copy_; shape propagation skips autograd. A
  write predicted in place that still runs in PyTorch, in a graph too small
  for an engine or in a block next to one, gets the copy_ back. Write-backs
  run without autograd, as a model's own write under torch.no_grad() does.
- **Buffers** keep main's rule, except that a buffer the engine gets a copy
  of, such as a float64 one under truncate_double, is copied back.
- **Every entry point** does this. torch.compile turns each written input's
  final contents back into write-backs; its fallback removes lowering's
  clones.
- The serialized engine and require_full_compilation refuse a write into an
  input they cannot do in place, even a slice assignment. Main dropped the
  write. The check that each predicted write was done in place also reads
  the engine module full compilation returns.

Not covered, as on main: torch_tensorrt.compile loses a write into an
nn.Parameter. Saving a module that keeps a write-back needs retrace=True;
otherwise torch.export's verifier rejects the kept copy_.

Tests compare with eager. Failing without this change: a functional write of
an input (index_copy and slice_scatter), caller writes not done in place, an
add_ and a copy_ into a caller's tensor, the example at the default
min_block_size (also under torch.compile), a write in a block left to
PyTorch next to an engine, a write under no_grad into a tensor that needs a
gradient, a write-back after a reader of the old contents, a copy only for
such readers, a strided cache written from a parameter, and its refit, a
float64 cache and cache buffer, torch.compile with a strided cache and with
a returned view on the fallback, full compilation, the serialized engine, a
saved module, the Windows cross compile, the cache key. Guards with a
mutant: torch.compile in place, a returned view on the engine path, the
engine cache, a renamed cache, the index_copy validator reading its own
input.

Signed-off-by: Anthony Shoumikhin <[email protected]>
@shoumikhin
shoumikhin force-pushed the kv-caller-tensor-writes branch from 57d4dad to 00fa762 Compare November 23, 2026 20:35
@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: conversion Issues re: Conversion stage component: converters Issues re: Specific op converters 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 component: torch_compile

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant