Skip to content

perf(executorch): replay KV cache engines, cut per-call copies and work - #5075

Merged
micwill755 merged 9 commits into
pytorch:mainfrom
shoumikhin:et-runtime-cuda-graphs-aliased-kv
Nov 25, 2026
Merged

micwill755 merged 9 commits into
pytorch:mainfrom
shoumikhin:et-runtime-cuda-graphs-aliased-kv

Conversation

@shoumikhin

@shoumikhin shoumikhin commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor

What is wrong today

With use_cuda_graphs on, the ExecuTorch TensorRT delegate records an engine's kernel launches once and replays them. Today:

  • An engine with aliased outputs, which writes an input in place (such as a decode step updating its key-value (KV) cache), never replays, so every decode step pays for every launch.
  • When only some buffers move between calls, all inputs and outputs are copied through buffers of the graph's own. A program that passes weights as engine inputs copies them all on every call and keeps a second copy on the GPU.
  • Every call repeats CPU work it rarely needs: cudaFree(nullptr) before each replay, a full cudaPointerGetAttributes per buffer, and a lookup and resize of each output's shape.
  • Some delegate C++ tests fail now and then, because device fills on the legacy default stream are not waited for.

What this change does

  • Copy only the moving buffers. Each input and output is tracked on its own. One that moves twice goes through a graph buffer. The others stay in place and are not copied.
  • Skip cudaFree(nullptr) when cuCtxGetCurrent finds a context. A call that overlaps another thread's global capture (unsupported) waits for its work, and does not turn replay off.
  • Ask where each buffer lives with one cuPointerGetAttributes for the 4 attributes needed.
  • Read output shapes once per change of input shapes, and resize an output only when its sizes differ.
  • Tests: destroying a graph checks its frees by address.
  • Tests: device fills wait for the legacy stream.
  • Tests: the output shape tests wait too.
  • Accept a peer-mapped buffer on another GPU from a thread with no current context.
  • Replay engines with aliased outputs. The cache stays on the caller's buffer, and calls run without the graph while it moves. At its second move away from the last recording, recording stops until 32 calls pass without another. A move with new shapes does not count, so separate prefill and decode buffers keep replaying decode.

What was tested

Linux x86_64, A100, TensorRT 11.4, CUDA 13.2, ExecuTorch 1.6 wheel, local CMake build of the C++ tests (not Bazel):

  • Every delegate C++ suite passes at the last commit, and the graph and scratch suites at every commit, apart from the flaky fills the test commits fix. 2-GPU cases are skipped.
  • Each fix has a test that fails without it.
  • Through the ExecuTorch Python runtime, a KV cache decode model (staged and zero-copy) and an MLP exported with CUDA graphs on match eager PyTorch at every step.
  • CI has not run the C++ suite: the wheel build fails on a header the PyTorch nightly dropped.

@micwill755 micwill755 left a comment •

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I reviewed the second commit only, since this is stacked on #5044. The logic looks correct to me. I traced shape changes, scratch growth, the other-context path and freeing the graph's buffers on stop, and found no out-of-range reads or misuse of stale buffers. The tests are thorough.

My main question is about design: once an engine stops replaying, it never replays again (comment on count_move). The other comments are minor.

ET_LOG(
Info,
"TensorRTBackend::execute: the buffer of an aliased output moved away from its CUDA graph twice, so the "
"engine runs every later call with enqueueV3; keep it in one buffer to replay");

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should this stop be permanent? moves_ never resets, even across shape changes, so two cache switches turn replay off for the engine's lifetime. ExecuTorch's memory planning keeps the cache in place, so typical programs won't hit this. Callers who manage their own caches will, though:

  • clone_outputs=False with a fresh cache per conversation loses replay at the second conversation.
  • A server alternating two cache slots every few hundred tokens loses replay at the second switch.
  • One-token prompts on the prefill buffer (already noted in the README).

Recording again once per switch costs very little next to hundreds of replayed decode steps. Could the count reset after N replays on one address, or only count moves that come within a few calls of a recording? That still stops a cache that moves on every call without punishing rare switches.

If the permanent stop stays, I'd log it as a Warning rather than Info, since the caller asked for replay and is losing it.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good point, the stop is no longer permanent. Once 32 calls pass without a counted move of the cache, the count starts over and the engine records again. So a new cache per conversation, or a server that switches slots every few hundred tokens, costs one call without a graph and one recording at each switch, and replays in between. A cache that moves twice within 32 calls still stops, so a cache that moves every few calls does not keep recording; in my measurements one recording cost about as much as 3 to 4 replays save, from 16 to 1024 layers. I kept the log at Info, since ExecuTorch's logging has no Warning level and the stop now ends on its own.

for (size_t i = 0; i < count; ++i) {
if (!staged_[i] && addresses[i] != recorded_[i]) {
count_move(i);
staged_[i] = moves_[i] > 1;

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: this also sets staged_[i] for the cache and its aliased output once moves_[i] > 1, and so does the shape-change loop at line 292. The header says they "never go on buffers_". Nothing breaks today because stopped() returns first. Guarding with !in_place_only(i) would make the code match the comment and protect against later changes.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done, both places now skip the cache and its aliased output. Since a stop can now end, this is more than a nit: without the guard, the first recording after a stop would put the cache on a buffer of the graph's own. A test checks that the recording after a stop stays on the caller's cache, with and without a shape change in between.

Error,
"TensorRTBackend::execute: an engine with aliased outputs replays a call on a stream of another regular "
"CUDA context only on the buffers of a CUDA graph its own calls recorded, and %s",
graph_exec_ != nullptr ? "this call brings other ones" : "there is none");

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

After the engine stops recording, graph_exec_ is always null, so a call from another context gets "...and there is none". That reads like the engine just hasn't recorded yet. Could this branch check stopped() and say that replay stopped because the cache buffer moved?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done. During a stop, a call from another context now gets "it records none while the buffer of an aliased output keeps moving", and a test checks that message.

that moves its buffers on every call, or alternates two sets, records once for each set of shapes in
each graph, as one that keeps them does, and both first replay on the 3rd call, unless the engine
has aliased outputs. Inputs and outputs that change at different calls each count on their own, so N
of them that change one after another can cost up to 3N+1 recordings for one set of shapes. Each

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nothing tests the 3N+1 recording bound. Could you add a test that moves two or three bindings one after another and checks the number of recordings?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added one. Three inputs move before the first recording, settle one after another, and then each moves twice. That reaches the bound exactly, 3N+1 = 10 recordings, and the next call replays. The docs now also say that the bound does not cover an aliased output and its input, which follow their own rule.

12.5 never replays. The delegate logs the reason.
- A GPU without stream-ordered memory, or a driver older than CUDA 12.5, never replays. The delegate
logs the reason.
- An engine with aliased outputs, such as one that updates a KV cache in place, keeps each aliased

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This bullet runs about 25 lines as one paragraph, and the same text is in executorch.rst. It would be easier to read split into the rule, then the examples (decode loop, separate prefill and decode buffers, one-token prompt), then the other-context behaviour.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Split it. The list item is now short, and a section below the list gives the rules for the cache buffer, then the examples (decode loop, separate prefill and decode buffers, one-token prompts, switching caches), then the other-context behaviour. executorch.rst has the same text.

@shoumikhin
shoumikhin force-pushed the et-runtime-cuda-graphs-aliased-kv branch 5 times, most recently from 6951b10 to 9f3cc19 Compare November 21, 2026 12:46
…fers

With CUDA graph replay on, the TensorRT delegate records the graph on the
caller's buffers while they stay put. Once they keep moving, it switches
every binding to buffers of its own, and every call copies all inputs in
and all outputs out.

That is costly when a program takes large inputs that never move, such as
weights passed in as engine inputs, while its outputs arrive at a new
address on each call, as they do through the ExecuTorch Python runtime.
Every call then copies all the weights, and each program keeps a second
copy of them on the device.

The graph now tracks each binding on its own. A binding that moves twice
goes through a buffer of the graph's own, as before. A binding that moves
while no graph is recorded does so until it repeats its address. Every
other binding stays on the caller's address and is not copied, and when
one of them moves, the graph records again on its new address. A buffer
no recording reads any more is freed at the next recording. When all
bindings move at the same calls and no call comes from another regular
CUDA context, this is the old behavior. Bindings that move at different
calls each count their own moves, so N of them can cost up to 3N+1
recordings for one set of shapes in each graph. A growth of the shared
scratch, a call from another regular CUDA context, or a recording that
fails or is skipped can add more. Some patterns record more often than
before, and a binding that moved twice while another waited for a
repeat stays copied after it stops moving.

A call from another regular CUDA context replays the graph when it brings
the same addresses for the bindings the graph reads and writes in place.
Otherwise it records on buffers of the graph's own for every binding, and
from then on every call on a plain stream copies every binding until the
shapes or the profile change. Such a call used to replay whenever the
graph already copied every binding, so it can now record, or fail, where
it used to replay. If that recording fails, the engine keeps its own
graph, as before. Calls from a green context are not affected, since
each green context keeps a graph of its own. The backend README, the user
guide and the documentation of the CUDA graphs option describe the new
behavior.

Tests in test_execution_graph.cpp:
- AnInputThatStaysPutIsReadInPlaceWhileTheOutputMoves: the input stays
  put and the output moves. The input is read in place, only one buffer
  is allocated, a replay copies only the output, and moving the input
  records again on its new address.
- AWeightInputStaysInPlaceWhileAnActivationInputMoves: with 3 inputs,
  a weight input stays put next to a longer activation input that moves
  twice. Only the activation is copied, in full, and the weight, the
  other input and every output stay in place. When the other input then
  moves twice too, both moving inputs are copied and the weight still is
  not.
- AnOutputThatMovesTwiceIsCopiedAloneWhileTheOtherOutputsStayPut: with
  3 outputs, only output_1 moves twice. It alone is copied out, in full
  although it is longer than output_0, and every input and the other
  outputs stay in place.
- BindingsThatMoveOneAfterAnotherReachTheBoundOfThreeRecordingsEachAndOne:
  3 inputs that move one after another record 3N+1 times for one set of
  shapes, and the last call replays.
- AnInputThatMovedBeforeTheFirstRecordingGoesBackInPlaceOnceItRepeats:
  the input goes back in place once it repeats and its buffer is freed,
  while the moving output is still copied.
- AStagedInputThatRepeatsWhileTheOutputMovesGoesBackInPlaceInOneRecording:
  an input that repeats on the call where the output moves goes back in
  place in that call's recording, so 4 calls record twice, and one that
  moves again on that call stays staged.
- NewShapesKeepOnlyTheBuffersThatMovedTwiceStaged: under new shapes the
  output that moved twice stays staged and the input stays in place.
- StagingCarriesAcrossShapeChanges: across 2 shape changes, the output
  that moved twice stays staged, the input that moved once does not, and
  an input staged until it repeats settles without the output.
- AlternatingSetsUnderNewShapesRecordOnceAfterAnOutputWasStaged: a caller
  that alternates 2 whole sets of buffers still records once for each
  set of shapes and first replays on the 3rd call.
- AFailedAllocationForAnInputKeepsAnOutputThatMovedTwiceStaged: when
  the buffer for an input that waits for a repeat cannot be allocated,
  that input goes back in place, and an output that moved twice stays
  staged, so later calls still record and replay.
- AnOutputThatWaitsForARepeatDoesNotCountTheMovesOfAnInput: an output
  staged until it repeats does not count the moves of the input next to
  it, so it goes back in place when it repeats.
- FailedRecordingsFromAnotherRegularContextLeaveAnOwnGraphThatCopiesOnlyItsOutput:
  a failed recording for another context keeps the engine's own graph,
  which still reads its input in place.
- ACallFromAnotherRegularContextReplaysAPartlyCopiedGraphOnItsInPlaceAddresses:
  a call from another context that brings the address the graph reads in
  place replays the graph without recording and copies only the output.
- CallsAlternatingWithAnotherRegularContextReplayOneGraph: calls that
  alternate with another context record once, then replay one graph
  instead of recording at every switch, and both contexts get the right
  outputs.
- AGreenContextGraphReadsAnInputThatStaysPutInPlaceWhileTheOutputMoves:
  on a green context stream too, the input is read in place while the
  output moves, and a replay copies only the output.

All new tests but the AlternatingSets one fail without this change. That
one guards behavior the change must keep.

Signed-off-by: Anthony Shoumikhin <[email protected]>
execute() calls cudaFree(nullptr) before every CUDA graph replay, before
every call on a default stream, and before every switch of optimization
profile, so that a thread with no current context gets the device's
primary context. Most calls come from a thread that already has a context,
and for them the call does nothing but still costs a trip into the CUDA
runtime on every run.

Ask the driver first with cuCtxGetCurrent, which only reads this thread's
state, and skip the cudaFree(nullptr) call when it reports a current context.
A thread that has not used CUDA yet still gets the primary context, and a
context the caller made current is still kept. This covers all three places
that make the call.

The README already says not to overlap execute() with a global CUDA graph
capture on another thread. Such a call on one of these paths used to fail
early at the cudaFree(nullptr), before it queued any work. With a context
current, it now goes further before it is refused, which has 2 effects.

First, it queues the engine. The capture also refuses the wait that
execute() makes before it returns an error, so the call could return while
the engine still wrote the outputs and the staging buffers, as a call on a
stream of the caller's own already could. That wait now runs in the relaxed
capture mode, which another thread's capture does not refuse, so execute()
does not return an error with its work still running. The exception is the
legacy default stream, where the capture refuses the wait in every mode.

Second, a call of an engine with CUDA graphs on can reach the recording of
its graph, where the capture refuses cudaGraphInstantiate, or the cudaMalloc
of the graph's own buffers. Such a refusal no longer counts against the
graph, so these calls do not turn graph replay off until the shapes change.

The README lists the calls that can break such a capture, and says all
this. The error logged when the final synchronize fails now names a capture
on another thread among its causes, on a line of its own, since ExecuTorch
prints only the first 255 characters of a log line.

The test of a call that overlaps another thread's capture runs it on a
thread that has not used CUDA, which still stops at the cudaFree(nullptr),
and on a thread with a context current, which queues the engine behind
slow host work and must not return before that work is done. Both return
Internal, leave no CUDA error pending, and leave the thread's capture mode
as it was. A new test checks that calls of a graph engine that overlap a
global capture leave replay on, both on the same addresses and on moved
ones. The test that checks a bad input is refused
before anything can break a global capture, and a new test of the same
refusal for a pooled engine with CUDA graphs on and a capturing stream,
make their call from a thread that has not used CUDA, where a
cudaFree(nullptr) moved above the refusal would run, so they still check
that order. The log length check in test_artifact_guard.py covers the new
line.

Signed-off-by: Anthony Shoumikhin <[email protected]>
execute() calls cudaPointerGetAttributes for every input and every output on
every call, to learn whether the buffer is device memory and whether it sits
on another GPU. With CUDA graphs on, these queries are a measurable part of
the time a call spends on the CPU.

cudaPointerGetAttributes asks the driver for more than execute() needs. Ask
it directly instead, with one cuPointerGetAttributes for just the 4
attributes that matter: the memory type, whether the memory is managed, the
device it was allocated on, and the address it has from the current
context. On an A100 host this takes about 84 ns per buffer, against about
136 ns before.

The answers are the same as before for device memory, an address inside a
device buffer, managed memory, pinned and mapped host memory, registered and
pageable host memory, freed memory and stream-ordered allocations. The
driver reports managed memory as device memory on most GPUs, and as host
memory with the managed flag set on a Jetson Orin, so managed memory is
still accepted by its own flag. Nothing is kept between calls, so a buffer
that was freed and came back as other memory, or a GPU whose peer access
was turned on or off, is seen on the next call.

New tests check that each buffer is asked about with one driver query per
call, that a buffer reported on another GPU is refused as an input, an
output or an aliased output unless this engine can reach it, and that
managed buffers are bound in place with no staging copies, also as an
aliased input, both as the driver reports them here and as a Jetson Orin
does. The source
checks in test_artifact_guard.py that guard the refusal of a buffer on
another GPU follow the new names, and pin both places that handle managed
memory.

Signed-off-by: Anthony Shoumikhin <[email protected]>
execute() asks TensorRT for every output's shape by name on every call, and
then resizes the ExecuTorch output tensor, even when the input shapes are the
same as on the call before. The lookup by name and the resize are both
repeated work for the common case of fixed shapes.

Read the output shapes right after inferShapes succeeds and keep them on the
handle. The delegate already runs inferShapes again whenever the input shapes
or the optimization profile change, so the kept shapes are always the ones
TensorRT would report. An output tensor, aliased or not, is resized only when
its sizes differ from them, so an output that something else resized between
calls is still set back to the right shape.

Signed-off-by: Anthony Shoumikhin <[email protected]>
…ffers, by address

DestroyFreesReplayBuffers counted every cudaFree the test wrapper saw while
the graph was destroyed and expected 2. In a build that links ExecuTorch's
CUDA extension statically, TensorRT's engine and context memory is released
through ExecuTorch's CUDA allocator inside the test binary, so the wrapper
counted 4 and the test failed although the graph freed its buffers.

The wrapper now records each freed pointer, and the test checks that each of
the graph's 2 replay buffers was freed exactly once.

Signed-off-by: Anthony Shoumikhin <[email protected]>
…gate C++ tests

Some delegate C++ tests fill a device buffer with cudaMemcpy from a
std::vector, or clear an output with cudaMemset, and then run the engine
on a non-blocking stream, or on a stream of another CUDA context. A copy
from pageable host memory, or a memset of device memory, can return
before it has landed on the device, and the legacy default stream it runs
on does not order work on those streams. So the engine could read an
input before it was filled, and the test then failed on wrong values now
and then. StridesWithoutADimOrderAreReadByTheirStrides showed it most
often. A memset that lands late would clear an output after the engine
wrote it in the same way.

The tests now wait for the legacy stream after each such copy or memset:
test_execution_graph through small copy_to_device and fill_device
helpers, and test_shared_scratch_backend where it fills its input and
output buffers. The pooled two-thread test no longer waits again after its
fill, since the fill now waits itself. Only tests change.

Signed-off-by: Anthony Shoumikhin <[email protected]>
The ExecutionGraph test for output shapes fills a device buffer with
cudaMemcpy from host memory, and clears the output with cudaMemset, and
then runs the engine on a non-blocking stream. The copy or memset runs on
the legacy default stream, which does not order work on that stream, so it
could land after the engine read the input or wrote the output, and the
test then failed now and then on a busy GPU. It now uses the
copy_to_device and fill_device helpers, which wait for the legacy stream,
like the other delegate tests. Only tests change.

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

execute() refuses a buffer on another GPU unless the driver gives it an
address from here, which is the case once peer access to that GPU is
turned on. The driver gives that address only for the current context. A
worker thread that has made no CUDA call yet has no current context, so
execute() refused a buffer it can use: an input, an output or an aliased
output on another GPU, with peer access on, called from such a thread,
returned InvalidArgument with a message asking to turn on a mapping that
was already on.

When the driver reports no address for a buffer on another GPU and no
context is current, execute() now asks again with the engine's context
pushed for that one query, since that is where the mapping is turned on.
Only that rare case pays for the second query and the push.

New steps in the test of buffers reported on another GPU run from a fresh
thread: a reachable input and a reachable output are accepted, which fails
without this change, and an unreachable input is still refused. The
test of a call that overlaps another thread's global capture now runs the
engine once before the capture starts, since TensorRT advises one enqueue
before any capture. The source check in test_artifact_guard.py follows the
new call, and the comments on the buffer query name the second query.

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

With use_cuda_graphs on, the TensorRT delegate never recorded a graph
for an engine with aliased outputs, which writes an input in place, such
as a decoder step that updates its KV cache. So a decode step paid for
every kernel launch even with replay on.

Replay is safe while the graph runs on the buffers it was recorded on,
and ExecuTorch's memory planning keeps a cache in one buffer from call
to call. The graph already follows each input and output on its own: one
that stays put is used in place, one that keeps moving goes through a
buffer of the graph's own. This change records engines with aliased
outputs too and adds one rule: an aliased output and the input it
updates never go on a buffer of the graph's own, since that would copy
the whole cache on every call.

Where the graph would move them to its own buffer, the call runs without
the graph, and the first call that repeats the previous call's buffer
records again. A cache that moves on every call never records, and the
engine logs that after 32 such calls. A move to another buffer than the
one of the last recording under the current shapes counts, and at their
second counted move the engine stops recording, logs that, and frees the
buffers the graph kept for its other inputs and outputs, also when the
cache alternates between two buffers. Once 32 calls pass without such a
move, its count of moves starts over and the engine records again, so a
new cache for each conversation, or a server that switches cache slots
now and then, keeps replaying between switches. A recording costs about
what 4 replays save. A move that comes with new shapes does not count,
nor does leaving a recording made under other shapes, so separate
prefill and decode buffers keep replaying decode. Other inputs and
outputs follow the usual rules, so a token or output at a new address on
every call is copied and decode still replays. A call from another
regular CUDA context replays only on the in-place buffers the graph was
recorded on, and otherwise fails with an error that says why.

Engines without aliased outputs behave as before. Nothing changes unless
use_cuda_graphs is on.

Signed-off-by: Anthony Shoumikhin <[email protected]>
@shoumikhin
shoumikhin force-pushed the et-runtime-cuda-graphs-aliased-kv branch from 9f3cc19 to 7e9b9a6 Compare November 23, 2026 23:59
@shoumikhin shoumikhin changed the title perf(executorch): replay CUDA graphs for engines that update a cache in place perf(executorch): replay KV cache engines, cut per-call copies and work Nov 23, 2026
@micwill755

Copy link
Copy Markdown
Collaborator

LGTM. Reviewed the whole PR, including the commits from #5044.

CI never reached executorch_backend_tests because the nightly build fails, so I ran them locally on 7e9b9a6 (RTX 5090, TensorRT 11.4). 356 passed, 6 skipped and none failed. The skips need a second GPU or an empty-batch case this GPU can't reach.

@micwill755
micwill755 merged commit aa2b7b8 into pytorch:main Nov 25, 2026
39 of 44 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

cla signed component: api [C++] Issues re: C++ API component: tests Issues re: Tests documentation Improvements or additions to documentation

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants