Skip to content

feat(conversion): write a dynamic-length prompt into the KV cache - #5100

Draft
shoumikhin wants to merge 13 commits into
pytorch:mainfrom
shoumikhin:kv-multitoken-zero-copy
Draft

shoumikhin wants to merge 13 commits into
pytorch:mainfrom
shoumikhin:kv-multitoken-zero-copy

Conversation

@shoumikhin

@shoumikhin shoumikhin commented Nov 22, 2026 •

Copy link
Copy Markdown
Contributor

This stacks on #5099, so please merge #5099 first. Only the last commit is new here. #5099 and the pull requests under it describe the other commits.

What is wrong today

An LLM decoder often does prefill and decode in one method. Each call writes a dynamic number T of new tokens into its KV cache:

idx = input_pos + torch.arange(k.shape[2], device=k.device)
self.k_cache.index_copy_(2, idx, k)

TensorRT's KV cache layer (IKVCacheUpdateLayer) writes this in place only when T is 1. For a longer prompt the engine returns a new cache, and a copy puts it back.

What this change does

  • Many tokens in place. The KV cache path of index_copy takes dynamic shapes. It writes in place when the index is one run, arange(n) alone or plus one value such as input_pos, as int32 or int64. Buffer lifting checks the run before constant folding hides it.
  • Writes that can be empty. The layer cannot write 0 tokens. A write whose size can be 0, as with Dim("T", max=8), runs in PyTorch with a warning, and its cache is copied back. compile, the Windows cross compile, torch.compile and refit decide this the same way, from the program's ranges. With require_full_compilation=True the write stays in the engine, so a call with 0 tokens fails. The guide says to export Dim("T", min=1, max=...).
  • The general index_copy converter needs a static index and source, because its scatter needs their sizes. Otherwise the write runs in PyTorch, also under assume_dynamic_shape_support. Under that setting a dynamic input still converts, as before.
  • CUDA graphs per engine record again when the token count changes.
  • Positions are not checked in place. TensorRT drops a write past the end of the cache, where PyTorch raises.

The prefill guide in the saving models page shows the pattern. It says the in-place write needs batch size 1 and a float32, float16 or bfloat16 cache.

Testing

New tests compare with eager: dynamic T in one engine, unknown head sizes, an index built in PyTorch, writes that can be empty under each entry point, a computed size, CUDA graphs, refit, and a dynamic input of the general converter. Each test fails when the code it checks is removed.

I ran the changed test files on Linux x86_64 with one NVIDIA GPU, with the C++ runtime built from this branch and with the Python runtime only.

@meta-cla meta-cla Bot added the cla signed label Nov 22, 2026
@github-actions github-actions Bot added documentation Improvements or additions to documentation 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
@github-actions
github-actions Bot requested a review from zewenli98 November 22, 2026 06:32
@shoumikhin
shoumikhin force-pushed the kv-multitoken-zero-copy branch 6 times, most recently from 9ca2df9 to d3e37a9 Compare November 23, 2026 19:56
… 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]>
…t how to set opt for exported programs

With require_full_compilation=True and every operator supported, compile
converts the whole graph as one engine and skips partitioning. That path
ignored Input.profiles. It built one profile, tuned for the export
example, that covered every entry, so optimization_profile(model, 1) had
no profile to select. The partitioned path builds one profile per entry,
and before the whole-graph path existed (2.14) this case took it too.

Build the profiles once, before the path is chosen, and use them on both
paths: each engine gets one profile per entry, and different profile
counts raise. This changes the whole-graph path for inputs with more than
one profile. A call outside profile 0 must now pick a profile with
optimization_profile, a size that no profile covers cannot run, and inputs
with different profile counts no longer compile. That is how the
partitioned path already works.

Match the Inputs to the graph inputs through the export input spec, as
_build_user_symbol_bounds already does, instead of by position. Without a
spec, for example after a mutated buffer becomes an engine input, match
kwargs by name and take the args in order, then any kwarg that names no
graph input, as export can rename an argument (X becomes x). Before,
kwargs passed in a different order than at export, a tuple input before a
profiled one, or a mutated buffer next to profiled kwargs gave an input
the profile of another input.

For an ExportedProgram, the engine opt comes from the export example, and
a plain Input(min_shape, opt_shape, max_shape) does not change it. Warn
once per compile when opt_shape differs from the example in a dynamic
dimension of the export that no profile covers, and document the two ways
to set opt: export with an example of that size, or pass the input as a
single entry in Input(profiles=[...]).

The 0/1 specialization message said the engine min would be 2, but the
engine keeps min 1. Make it a debug message that says so.

Signed-off-by: Anthony Shoumikhin <[email protected]>
The warning that a plain Input.opt_shape does not set the engine opt was
logged before compile_module knew whether TensorRT would get any part of
the graph, so a compile that converts nothing still warned about an
engine. _build_user_symbol_bounds now returns the dims it would warn
about, and compile_module warns on the whole-graph path, and on the
partitioned path only when a TensorRT part exists. The input checks in
_build_user_symbol_bounds still run where they did.

The unit tests that exported at their opt_shape only to avoid the old
warning go back to their original examples, and the guide says when the
warning is logged.

Signed-off-by: Anthony Shoumikhin <[email protected]>
The 0/1 specialization test passed whether or not the branch ran, so
check its debug record.

Signed-off-by: Anthony Shoumikhin <[email protected]>
save_dynamic_shapes_example.py exported its first model at batch 2 with
opt_shape batch 8, so the engine was tuned for batch 2. Export it at
batch 8.

Signed-off-by: Anthony Shoumikhin <[email protected]>
Engine profiles of dynamic sizes and the Input spec check read PyTorch's
shape system, which assumes sizes of at least 2:

- A size computed from a Dim, such as 2 * n rows from cat((x, x)) in
  PyTorch, starts at 4 when n can be 1, t + 1 from Dim("t", min=0) at 3, and
  an Input spec of n does not bound it.
- The Input spec check reads Dim(min=1) as min 2, so min_shape=1 looks the
  same for Dim(min=1) and a Dim(min=2).

- **Computed sizes.** A computed size takes its range from its symbols: the
  program's smallest value (range_constraints), bounded by Input specs. A
  recorded minimum is never lowered, except export's 2 for the b of 2 * b,
  which 2 * b's record corrects, and a 2 that an Input spec starts at 1. So
  with Dim(min=1), 2 * n starts at 2; t + 1 starts at 1, and b + 1 from
  Dim("b", min=2) at 3. Dim.DYNAMIC and Dim.AUTO record 2, so their 2 * n
  starts at 4 unless a spec starts n at 1. The spec of an input of 2 * b
  rows bounds b inside its exported range, unless that input has profiles.
  On the torch.compile path, which has no range_constraints, 2 * s starts at
  2 instead of 4. A computed size with no max keeps the max it had.
- **Inside the specs.** A spec can rule out the traced size, so opt comes
  from one value per symbol, moved inside its range, and related inputs
  (n + m, 2 * n) agree. Whole-module CUDA graphs warm up inside the specs.
  The opt_shape warning compares with that opt, so it also covers an example
  outside the Input range.
- **Messages.** Dim(min=2) with min_shape=1 warns that the program was not
  exported for 1; Dim(min=1) does not. min_shape=0 for a bounded Dim, a
  max_shape below the program's minimum, and a 2 * b spec outside b's range
  get clear messages. A spec that pins a dim to 1 compiles.

Tests compare with eager. Failing without this change: 2 * n bounded by
specs on both inputs; t + 1 from Dim("t", min=0), at 0; b + 1 from 2 * b
rows sliced in PyTorch; 2 * b rows refuse 1; a 2 * b spec inside and outside
b's range; cat((x, y)) with a spec ruling out the traced size; a dim pinned
to 1, also through cat((x, x)) in PyTorch; the opt_shape warning with a spec
of 2 * n. Guards with a mutant: Dim("b", min=2) refuses 2 rows through
b + 1; CUDA graphs with a narrowed spec; a profiled 2 * b input leaves b
alone.

Signed-off-by: Anthony Shoumikhin <[email protected]>
A decoder doing prefill and decode in one method writes a dynamic number T
of tokens per call:

    idx = input_pos + torch.arange(k.shape[2], device=k.device)
    self.k_cache.index_copy_(2, idx, k)

Only T = 1 was written in place with IKVCacheUpdateLayer; for T > 1 the
cache was copied back.

- **Multi-token writes in place.** The index_copy fast path takes dynamic
  shapes and writes a run whose index is arange(n), alone or plus one
  value such as input_pos, int32 or int64. Buffer lifting proves the run
  before constant folding hides how the index was built. Unresolved head
  dimensions come from the static cache.
- **Writes that can be empty.** The layer cannot write 0 tokens. So a
  write whose index or source can be empty, as with Dim("T", max=8), runs
  in PyTorch, with a warning, and its cache is copied back. The program's
  ranges decide, also when a size is computed (6 * b from 3 * b), and compile,
  the Windows cross compile, torch.compile and refit decide alike. With
  require_full_compilation the write stays in the one engine, so a 0-token
  call fails there. The guide says Dim("T", min=1, max=...), which keeps
  the write in place.
- **The general converter needs a static index and source**, since its
  scatter needs their sizes, so a write with a dynamic index or source runs
  in PyTorch, also under assume_dynamic_shape_support. A dynamic input
  still converts there.
- **CUDA graphs per engine** record again when the token count changes,
  since it is now a shape input.
- Positions are not checked in place, and must fit in 32 bits. TensorRT
  drops a write past the end and wraps a negative position down to minus
  the cache length, where PyTorch fails.

Tests compare with eager. Failing without this change: dynamic T in place in
one engine (also with full compilation), unknown heads, an index built in
PyTorch, the Windows cross compile keeping a write of Dim("T", max=8) out of
the engine, assume_dynamic_shape_support keeping other dynamic writes in
PyTorch. Guards with a mutant: an index that is not one run, compile and
torch.compile keeping a write that can be empty in PyTorch, a doubled length
from a derived Dim that can be 0, CUDA graphs with another token count,
refit splitting the graph as compile did, a dynamic input with a static
index and source converting under assume_dynamic_shape_support, also when
the input can be empty.

Signed-off-by: Anthony Shoumikhin <[email protected]>
@shoumikhin
shoumikhin force-pushed the kv-multitoken-zero-copy branch from d3e37a9 to 94019ab Compare November 23, 2026 20:35
@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 documentation Improvements or additions to documentation

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant