Skip to content

fix(executorch): cut the CPU work each delegate call repeats, and fix the delegate C++ tests - #5052

Closed
shoumikhin wants to merge 7 commits into
pytorch:mainfrom
shoumikhin:executorch-host-cost
Closed

shoumikhin wants to merge 7 commits into
pytorch:mainfrom
shoumikhin:executorch-host-cost

Conversation

@shoumikhin

@shoumikhin shoumikhin commented Nov 16, 2026 •

Copy link
Copy Markdown
Contributor

What is wrong today

The delegate repeats CPU work on every call.

  • cudaFree(nullptr) before every CUDA graph replay, default-stream call, and profile switch, though only a thread with no context needs it.
  • cudaPointerGetAttributes for every buffer, which asks for more than needed.
  • A lookup and resize of each output's shape, even when input shapes are unchanged.

Some delegate C++ tests fail now and then. Their buffer fills on the legacy default stream are not waited for, and DestroyFreesReplayBuffers counts TensorRT's own frees in some builds.

What this change does

  • Ask cuCtxGetCurrent first, and skip cudaFree(nullptr) when a context is current. A call overlapping another thread's global capture (unsupported) then gets further, so its final wait runs in relaxed capture mode (except on the legacy default stream, as the README notes), and a recording refused by that capture does not turn replay off.
  • Ask where each buffer lives with one cuPointerGetAttributes for the 4 attributes needed. Same answers, also for managed memory (host memory on a Jetson Orin), except a peer-mapped buffer on another GPU is now also accepted from a thread with no current context.
  • Read output shapes once per inferShapes, and resize an output only when its sizes differ.
  • The error after a failed final synchronize prints its causes on a second line, within ExecuTorch's 255-character limit.
  • Tests: DestroyFreesReplayBuffers checks frees by address, and fills wait for the legacy stream.

What was tested

  • New tests, each failing without its code: a replay with a context skips cudaFree(nullptr); one driver query per buffer; a reachable buffer on another GPU is accepted from a fresh thread; overlapped calls leave replay on; an output of matching size is not resized.
  • New checks, each failing when their code is removed: an unreachable buffer is refused from a fresh thread; managed buffers need no staging copies; an overlapped call waits for its work and restores the capture mode; the log line fits.
  • A100, TensorRT 11.4, a local CMake build (not the Bazel targets): every C++ delegate suite passes at the last commit, the graph and scratch suites at every commit. CI did not reach these tests: the wheel build fails on a header that the current PyTorch nightly no longer ships, and main includes it too.
  • Measured: cudaPointerGetAttributes 136 ns, new query 84 ns; cudaFree(nullptr) 78 ns, cuCtxGetCurrent 11 ns.

@meta-cla meta-cla Bot added the cla signed label Nov 16, 2026
@github-actions github-actions Bot added component: tests Issues re: Tests component: api [C++] Issues re: C++ API labels Nov 16, 2026
@shoumikhin
shoumikhin force-pushed the executorch-host-cost branch 2 times, most recently from c77a80a to 42cf188 Compare November 18, 2026 19:18
@shoumikhin shoumikhin changed the title fix(executorch): cut the CPU work each call repeats in the ExecuTorch delegate fix(executorch): cut the CPU work each delegate call repeats, and fix the delegate C++ tests Nov 18, 2026
@shoumikhin
shoumikhin force-pushed the executorch-host-cost branch 7 times, most recently from f917e26 to b7c818a Compare November 22, 2026 00:30
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]>
@shoumikhin

Copy link
Copy Markdown
Contributor Author

Folded into #5075 to keep the number of PRs down. This PR's commits are in #5075.

@shoumikhin shoumikhin closed this Nov 23, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant