Skip to content

fix(conversion): keep non-float caches off the KV cache layer - #5098

Draft
shoumikhin wants to merge 7 commits into
pytorch:mainfrom
shoumikhin:kv-cache-layer-gate
Draft

shoumikhin wants to merge 7 commits into
pytorch:mainfrom
shoumikhin:kv-cache-layer-gate

Conversation

@shoumikhin

@shoumikhin shoumikhin commented Nov 22, 2026 •

Copy link
Copy Markdown
Contributor

This builds on #5097. Only the last commit is new here.

Torch-TensorRT can update a KV cache in place with IKVCacheUpdateLayer. When
it plans to, it drops the cache's copy_ before partitioning. The layer takes
only float32, float16 and bfloat16 caches, but the checks that pick it did
not look at the type:

  • An int32 or int64 cache written by index_copy or by slice assignment was
    sent to the layer, and the compile failed or the engine did not build.

  • A float64 buffer compiled with truncate_double was sent to the layer too,
    which updated a float32 copy, so the buffer lost the write.

  • A uint8 write on the cache dimension was refused at compile time.

  • The general index_copy converter took int8 writes and float64 writes
    without truncate_double, which TensorRT's scatter cannot build.

    self.cache.index_copy_(2, input_pos, x) # self.cache is int64

What changes:

  • The slice_scatter and index_copy checks that pick the layer accept only
    the three types it takes, from one shared list.
  • lift_mutated_buffers asks the same checks before partitioning. So a buffer
    of another type is copied back after each call, its write uses the scatter
    or concatenation fallback (a uint8 write runs in PyTorch), and an integer
    caller cache keeps its write-back copy_, as a float64 one already does.
  • A validator keeps int8 writes, and float64 writes without
    truncate_double, off the general index_copy converter, so they run in
    PyTorch.

float32, float16 and bfloat16 caches keep the in-place path.

Tests compare with eager PyTorch over three calls. Failing without this
change: int32 and int64 caches, buffers written by index_copy and by slice
assignment and a caller's tensor written by index_copy; a float64 buffer
with truncate_double; int8 and float64 writes, which now run in PyTorch. The
existing uint8 test in test_dtype_support.py now expects the write to work.

@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: runtime component: dynamo Issues relating to the `torch.compile` or `torch._dynamo.export` paths component: torch_compile labels Nov 22, 2026
@meta-cla meta-cla Bot added the cla signed label Nov 22, 2026
@github-actions
github-actions Bot requested a review from apbose November 22, 2026 02:20
@shoumikhin
shoumikhin force-pushed the kv-cache-layer-gate branch 7 times, most recently from 99f2a7d to 59ed530 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]>
Two reads of a cache from before its write saw the value after it:

- A buffer stored from a caller's cache that the same forward then writes,
  as in self.buf.copy_(cache) followed by cache.index_copy_(2, pos, x).
  Forward writes the buffer after the graph has run, so the buffer got the
  cache with the new rows. On main the buffer was never written.
- A KV cache buffer read before its write, as in
  old = self.cache.clone() followed by self.cache.index_copy_(2, pos, x).
  The buffer was updated in place on eligibility alone, so the engine could
  write it before the read. Main does the same.

A caller's cache that a buffer stores is now copied before the write, like
the other readers of its old contents. A buffer write is done in place only
when nothing else reads the old contents, the same check a caller's cache
already gets. Otherwise the buffer is copied back after each call. That
check looks through copy(cache, write) to the write, so the mark goes on the
write itself, as for a caller's cache.

Tested against eager over two calls: the stored buffer, a clone or a sum
of a cache buffer taken before its write, and a buffer write wrapped in a
copy. The tests fail without this change.

Signed-off-by: Anthony Shoumikhin <[email protected]>
TensorRT updates an aliased input (a KV cache, or a plugin input declared as
an alias) in place while the engine reads its other inputs. That breaks
when:

- **Memory is shared.** An input in a cache's memory, such as cache[:, :,
  :4], is read before or after the write. Two caches that share elements
  overwrite each other.
- **The input is copied.** A host, strided, negative or conjugate input is
  bound to a copy, so the caller loses a write the model does not return.
- **CUDA graphs run per engine.** A replay writes at the recorded address,
  of a freed copy or another input.

In both runtimes, deciding alike and before anything else runs:

- A call where a cache may share an element with another input is refused.
  Views of one layout sharing memory but no element, such as interleaved
  caches kv[..., 0] and kv[..., 1], work. A plugin input may be the same
  tensor as another input (x.add_(y) with x and y the same reads both
  first), unless both are updated and one is copied. A partial overlap is
  refused, as eager refuses it.
- The check reads only sizes, strides and addresses, so it works inside a
  CUDA graph. TorchTensorRTModule checks the caller's inputs itself when the
  call would copy one. While Dynamo traces it, it skips this and the copy
  below, as on main, since Dynamo cannot trace the view checks.
- A copied aliased input gets the copy's new contents, also in a module made
  without an alias map. That copy runs without autograd, as a write under
  no_grad does, so an input that needs a gradient gets it too.
- With CUDA graphs per engine, a copied aliased input is refused, and one at
  a new address records again, so addresses no longer have to stay fixed.
  A call that fails before the graph is recorded makes the next call record
  again.

Refused although eager works: a reader of a slot the call does not write,
and overlapping layouts with different dimensions. The Python check runs on
every call with aliased inputs: 43 microseconds for 56 separate caches, a
few milliseconds for 64 interleaved in one buffer.

Still as on main: whole-module CUDA graphs lose caller cache writes.

Both runtimes, compared with eager. Failing without this change: views of
the cache and caches sharing elements are refused; a copied cache keeps
every write, also without an alias map; interleaved caches keep both writes;
a copied cache that needs a gradient gets its write; a plugin input sharing
a cache or part of another input is refused; CUDA graphs refuse copied
caches and record again for new ones, also after a failed call; the check
costs little when no cache is copied. A randomized test checks the Python
decision element by element.

Signed-off-by: Anthony Shoumikhin <[email protected]>
Torch-TensorRT can update a KV cache in place with IKVCacheUpdateLayer. When
it plans to, it drops the cache's copy_ before partitioning. The layer takes
only float32, float16 and bfloat16 caches, but the checks that pick it did
not look at the type:

- An int32 or int64 cache written by index_copy or by slice assignment was
  sent to the layer, and the compile failed or the engine did not build.
- A float64 buffer compiled with truncate_double was sent to the layer too,
  which updated a float32 copy, so the buffer lost the write.
- A uint8 write on the cache dimension was refused at compile time.
- The general index_copy converter took int8 writes and float64 writes
  without truncate_double, which TensorRT's scatter cannot build.

    self.cache.index_copy_(2, input_pos, x)  # self.cache is int64

What changes:

- The slice_scatter and index_copy checks that pick the layer accept only
  the three types it takes, from one shared list.
- lift_mutated_buffers asks the same checks before partitioning. So a buffer
  of another type is copied back after each call, its write uses the scatter
  or concatenation fallback (a uint8 write runs in PyTorch), and an integer
  caller cache keeps its write-back copy_, as a float64 one already does.
- A validator keeps int8 writes, and float64 writes without
  truncate_double, off the general index_copy converter, so they run in
  PyTorch.

float32, float16 and bfloat16 caches keep the in-place path.

Tests compare with eager PyTorch over three calls. Failing without this
change: int32 and int64 caches, buffers written by index_copy and by slice
assignment and a caller's tensor written by index_copy; a float64 buffer
with truncate_double; int8 and float64 writes, which now run in PyTorch. The
existing uint8 test in test_dtype_support.py now expects the write to work.

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

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: runtime component: tests Issues re: Tests component: torch_compile

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant