Repository navigation
CUDA backend: add a share_weights option, and stop low-memory mode from freeing GPU weights - #24937
Conversation
🔗 Helpful Links🧪 See artifacts and rendered test results at hud.pytorch.org/pr/pytorch/executorch/24937
Note: Links to docs will display an error until the docs builds have been completed. ❌ 1 Cancelled Job, 2 Pending, 1 Unrelated FailureAs of commit 0f46c7b with merge base e01c6a0 ( CANCELLED JOB - The following job was cancelled. Please retry:
BROKEN TRUNK - The following job failed but were present on the merge base:👉 Rebase onto the `viable/strict` branch to avoid these failures
This comment was automatically generated by Dr. CI and updates every 15 minutes. |
|
@claude /pr-review |
|
Claude finished @shoumikhin's task in 28m 13s —— View job Request changes: without the deep copy, lowering a GPU buffer that the graph writes, with Detailed reviewPR Review: #24937SummaryThe PR shares state-dict tensors in
Nothing was run on a GPU here. The first finding comes from reading the code and the repo's own notes on AOTI. Backward Compatibility
API Design
Testing
RecommendationRequest Changes The test that should catch lowering writing the caller's buffers cannot fail. Reading the code, that write happens when |
5e9fefe to
67ae9b4
Compare
|
@claude /pr-review |
|
Claude finished @shoumikhin's task in 22m 57s —— View job Request changes: the copies this PR makes of GPU buffers the graph writes are counted as the caller's tensors, so Detailed reviewPR Review: #24937SummaryThe PR shares state-dict tensors in
Nothing was run here, since there is no GPU. The findings come from reading the code. Testing
API Design
Backward Compatibility
Performance
RecommendationRequest Changes The buffer copies this PR adds are never freed or parked, so each GPU KV cache stays duplicated on the GPU after its method's preprocess ends. Cloning in |
67ae9b4 to
6eaab70
Compare
|
@claude /pr-review |
|
Claude finished @shoumikhin's task in 31m 9s —— View job Request changes: with Detailed reviewPR Review: #24937SummaryThe PR shares state-dict tensors with the caller in every mode of
Nothing was run here, since there is no GPU and torch's source wasn't available to read. The findings come from reading the code. Code Quality
Testing
API Design
Backward Compatibility
RecommendationRequest Changes The clone path this PR adds breaks lowering of a graph that writes a GPU parameter when compile-time autotune is off. The fix is one line. The PR now shares written GPU buffers with the compile, so it also needs an end-to-end test of them in both autotune modes. Tasks
The shallow checkout has no merge base with |
6eaab70 to
51302f2
Compare
|
@claude /pr-review |
|
Claude finished @shoumikhin's task in 33m 18s —— View job Approve: four minor issues remain: the OOM parking fallback may free weights that a candidate reads when Detailed reviewPR Review: #24937SummaryThe PR makes Code Quality
Testing
API Design
RecommendationApprove The blockers from the earlier rounds are resolved. The four findings above are minor and can be fixed in this PR or in a follow-up. Review steps:
|
51302f2 to
f4fc238
Compare
|
@claude /pr-review |
|
Thanks for the reviews. Status after the new push:
|
f4fc238 to
8e45925
Compare
|
Claude finished @shoumikhin's task in 46m 35s —— View job Approve: nothing blocks merging, but five minor issues remain: a low-confidence risk in how the no-spec Detailed reviewPR Review: #24937SummaryBefore this PR, No blocking issues were found. Five minor ones are below, and three of them are still open from the previous review: the duplicated tensor walk, the missing value check, and the undocumented rule against mutating shared tensors. This was a static review: no tests were run. Torch's source could not be read here, so the first Code Quality item relies on the PR's own description of Inductor's default. Code Quality
Testing
API Design
RecommendationApprove Nothing blocks merging. The no-spec autotune item is the only one that could affect correctness. It is low confidence, and an end-to-end test already guards it on GPU CI's torch. The other four are a duplicated walk, docstrings and test gaps. Review steps
|
|
Thanks for digging into this. The 16.1 → 8.2 GiB peak reduction is a nice win. I have a few concerns about the approach, mostly about making tensor sharing the default. Sharing tensors by default feels riskyBefore this change, only low_memory_mode shared tensors (via the deepcopy memo, from #21798). That was a deliberate trade-off for memory-constrained exports: users opted in and accepted weaker isolation to fit the model. This PR makes the same sharing the default for every CUDA export. So the default path now relies on preprocess never mutating a tensor it shares with the caller. Correctness now depends on finding and guarding every in-place mutation point: release_moved_tensors, autotune parking, and graph-written buffers when compile-time autotune is off. If someone later adds an in-place pass to preprocess (weight packing, copy_, resize_, etc.), it would quietly corrupt the caller's weights, and nothing would fail. That raises a broader question: why change the default instead of reusing low_memory_mode? The guards this PR adds (caller_storages in release, parking and tracking) are needed to fix low_memory_mode for GPU-resident weights anyway. Once they're in, users who keep weights on the GPU and are short on memory could just turn on low_memory_mode and get the same peak reduction. The default path would keep full deepcopy isolation. So what does this PR give us over "base + the low-memory fix + low_memory_mode=ON"? Is it that low-memory mode has costs you want to avoid here, like disk offload during autotune, KV-cache resizing, or file-backed blobs (slower compile, weights coming back at new addresses)? Or is it that you expect most GPU-resident users won't know to opt in? If it's the former, a narrower option could also work: a separate spec that only turns on tensor sharing. That keeps the risk opt-in. If we do keep sharing as the default, I'd like a cheap guard against regressions. At the end of preprocess, assert that every tensor in caller_storages still has the same data_ptr(), the same untyped_storage().nbytes(), and the same _version. A future in-place mutation of caller weights would then fail loudly instead of silently corrupting them. Track what the move created instead of what the caller owns, and keep the hook signaturecaller_storages is computed twice right now: in AotiBackend.preprocess and again in CudaBackend.move_program_to_device. It also forces a signature change on release_moved_tensors, which breaks out-of-tree AotiBackend subclasses that override it. A simpler alternative is to invert the bookkeeping. move_program_to_device already compares each tensor's storage before and after the move, and _MOVED_TENSORS already holds the result. We could record the tensors the move (or the write-clone path) created, and have release_moved_tensors and parking act only on that set. Then: there's one source of truth, owned by the move; Longer term: does compilation need real weights at all?With autotune_at_compile_time on, which is the AOT default, autotuning uses random inputs. The real weight bytes seem to matter only at serialization. If that holds, a cleaner design would be to compile against fake or meta stand-ins and stream the weights straight from the caller's tensors into the blob. That would remove the share-vs-copy question for both host and GPU memory. I know this is a bigger change. Inductor paths that need real values, like constant folding, would have to be handled or kept off. I'm not asking for it in this PR, but I'd like to know whether you think it's feasible, since it would affect how much we keep investing in the guard-based approach. |
d1f31a8 to
eb3aa01
Compare
Fair point. Sharing is opt-in now, and the default is the deep copy again, same as main.
Yes, that's the reason. Low-memory mode also offloads weights to disk during autotune (they come back at new addresses), makes CPU clones and resizes the KV cache. So I went with your narrower option: a new The guards are still needed either way: on main,
Since sharing is opt-in now, I left the assert out.
Done your way. The move records the tensors it created, and with sharing on, release and parking act only on that set. A tensor missing from the set is kept, not freed.
I think it's doable with compile-time autotune on. The blockers I see are constant folding, the small constants Inductor reads while compiling, and the autotune-off path, which runs on real values. Worth its own issue. |
|
@claude review |
|
Claude finished @shoumikhin's task in 5m 6s —— View job Approve: nothing blocks merging. Two minor issues remain: Detailed reviewPR Review: #24937SummaryThe PR adds an opt-in API Design
Code Quality
RecommendationApprove Neither finding blocks merging, and both only matter when sharing is on, which is now opt-in. Review steps
|
eb3aa01 to
4c6d9db
Compare
|
@claude review |
|
Claude finished @shoumikhin's task in 4m 57s —— View job Approve: nothing blocks merging. Three minor issues remain: when no Detailed reviewPR Review: #24937SummaryThe PR adds an opt-in Nothing was run here: there is no GPU, and torch's source couldn't be read. The first finding depends on Inductor internals, so it is low confidence. Code Quality
API Design
RecommendationApprove None of the three findings blocks merging, and all of them apply only when sharing is on, which is now opt-in. The first one could affect correctness, but it is low confidence. Making Review steps
|
|
stamp and please check the minor feedbacks of the last round of claude review |
test_replace_int64_floordiv.py imported the backend as backends.cuda.cuda_backend. When pytest collects it together with the other CUDA tests, Python loads cuda_backend.py a second time under that name, so two classes named CudaBackend exist. When lowering a program, exir looks up the backend class by name and runs the second copy. A test that patches CudaBackend and then lowers a program would not see its patch. Import the backend and the passes as executorch.backends.cuda..., like the other CUDA tests do. test_move_cond_predicate_to_cpu.py had the same kind of import for its pass, so change it too.
… them on the GPU copy_exported_program_for_preprocess deep-copied the program unless low-memory mode was on. A deep copy of a CUDA tensor is a new CUDA tensor, so lowering a program whose weights already live on the GPU needed twice their size in GPU memory, and large models ran out of memory while lowering on GPUs that run them fine. Share the tensors in the copy, as low-memory mode already does. Preprocess replaces state dict entries when it moves them; it does not change the weights. When compile-time autotune is off, Inductor runs the graph once on the real tensors, so move_program_to_device then gives each GPU buffer or parameter the graph writes its own copy. That copy counts as created by the move, so it is freed and may be parked like any other moved tensor. With compile-time autotune on, the default, nothing is copied. The copy also kept two later steps away from the caller's GPU weights: release_moved_tensors empties the moved program's CUDA tensors, and autotune parks the moved tensors on the CPU when a timing runs out of memory. AotiBackend.preprocess now records the program's storages before the move and passes them to release_moved_tensors, which frees every other CUDA tensor of the moved program. move_program_to_device records only the GPU tensors the move created, and autotune parks only those. This also fixes low-memory mode, which already shared the tensors and so could empty weights that start on the GPU. With weights that start on the GPU, the list autotune may park can hold nothing parkable, so its out-of-memory fallback skips the parked retry then instead of retrying with nothing freed. In low-memory mode, Inductor still moves the weights to disk while it autotunes, including weights the caller keeps on the GPU. They come back with the same values at new addresses. That is the memory saving low-memory mode asks for, and the docstrings now say so.
The comments above the out-of-memory fallback and above _MOVED_TENSORS said that parking the moved tensors on the CPU is safe because AOTI autotunes on random inputs. That holds only with autotune_at_compile_time on. With it off, Inductor first runs the graph on the real tensors, as the comment in move_program_to_device says, so a candidate timed in that pass can read a parked tensor. Both comments now say when parking is safe and, in the timing module, what happens when it is not. The docstring of copy_exported_program_for_preprocess pointed only at _MOVED_TENSORS for "never frees or parks". That list guards parking. Freeing is guarded by the caller storages, which release_moved_tensors leaves alone, so the docstring now points at both.
Sharing the program's tensors with the caller in every export made the default path depend on preprocess never writing a shared tensor. The default copy is deep again, as before this change, so existing exports keep full isolation. A new compile spec, share_weights, turns on the sharing alone, without the other low-memory steps (moving the weights to disk while autotuning, CPU clones of written buffers, emptied KV caches). Low-memory mode still shares as before. The bookkeeping now lives in move_program_to_device. When the tensors are shared, it records only the CUDA tensors it created, and release_moved_tensors frees only those, as autotune parking already did. A tensor the record misses is kept, not freed. release_moved_tensors keeps its signature, and AotiBackend.preprocess is unchanged. Without sharing, release frees every CUDA tensor of the program, as before.
…weights=OFF in low-memory mode Without an autotune_at_compile_time spec, the compile options left the setting to Inductor, while move_program_to_device guessed Inductor's default on its own to decide whether to copy the GPU tensors the graph writes. The compile options now always pass the value that move_program_to_device uses, so the two cannot disagree. Low-memory mode always shares the weights, so it silently ignored share_weights=OFF, and it never checked the share_weights value. share_weights is now read and checked first, and setting it to OFF together with low_memory_mode raises a ValueError. The CUDA overview now says that with autotune_at_compile_time OFF, the GPU buffers and parameters the graph writes are still copied, and that low-memory mode always shares the weights.
4c6d9db to
0f46c7b
Compare
|
@claude review effort=max |
|
Claude finished @shoumikhin's task in 42m 25s —— View job Approve, with minor findings. The main one: every CUDA export now forces Detailed reviewPR Review: #24937SummaryThe PR adds a Backward Compatibility
API Design
Testing
Performance
RecommendationApprove. Nothing here blocks merging. I'd still limit the Review steps
|
Title: CUDA backend: add a share_weights option, and stop low-memory mode from freeing GPU weights
What is wrong today
Before preprocess, lowering with
CudaPartitionercopies the program. By default the copy is deep. A deep copy of a CUDA tensor is a new CUDA tensor, so when the weights are already on the GPU, lowering needs about twice their size in GPU memory. A model whose weights take more than about half of the GPU cannot be lowered on that GPU, even though it runs there.Low-memory mode skips that copy and shares the tensors with the caller. But the rest of preprocess expects private copies, so with weights on the GPU it changes the caller's tensors:
release_moved_tensorsempties every CUDA tensor of the program, including the caller's weights.What this change does
A new compile spec,
share_weights(defaultOFF), turns on the sharing without the other low-memory steps. The default stays a deep copy, so existing exports do not change. Low-memory mode still shares.When sharing,
move_program_to_devicerecords only the CUDA tensors it creates, and release and autotune parking act only on those. A tensor missing from that record is kept, not freed. Hook signatures do not change.When sharing with compile-time autotune off, Inductor runs the graph on the real tensors, so the move gives each GPU buffer or parameter the graph writes its own copy.
If autotune has nothing it can park, its out-of-memory fallback skips the parked retry.
Low-memory mode always shares, so
share_weightsOFFwithlow_memory_modeONnow raises aValueError. Without anautotune_at_compile_timespec, the backend now passes its own resolved value to Inductor, so the move and the compile always agree. For CUDA that is the value Inductor already used, so default exports do not change.With PyTorch 2.15, low-memory mode still lets Inductor move the weights to disk while it autotunes, so the caller's GPU weights come back at new addresses, with the same values.
share_weightsalone does not do this.Tests
share_weights: a GPU buffer the graph writes stays unchanged; a two-method export keeps the weights' addresses and values and adds less than twice their size; weights moved from the CPU are freed, also afterrun_decompositionsrebuilds the program.share_weightsand low-memory conflict, and the move and compile agreeing on autotune when no spec is given.test_replace_int64_floordiv.pynow imports the backend asexecutorch.backends.cuda.cuda_backend. Its oldbackends.cuda.cuda_backendimport loaded a secondCudaBackendclass when pytest collected it with the other CUDA tests. Lowering finds the backend class by name, so it ran that second copy, and a test that patchesCudaBackenddid not see the call.share_weights.