Skip to content

CUDA backend: add a share_weights option, and stop low-memory mode from freeing GPU weights - #24937

Merged
shoumikhin merged 5 commits into
pytorch:mainfrom
shoumikhin:cuda-preprocess-share-gpu-weights
Nov 21, 2026
Merged

shoumikhin merged 5 commits into
pytorch:mainfrom
shoumikhin:cuda-preprocess-share-gpu-weights

Conversation

@shoumikhin

@shoumikhin shoumikhin commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor

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 CudaPartitioner copies 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:

  • At the end of preprocess, release_moved_tensors empties every CUDA tensor of the program, including the caller's weights.
  • When an autotune timing runs out of GPU memory, autotune parks those tensors on the CPU and puts them back at new addresses.

What this change does

  • A new compile spec, share_weights (default OFF), 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.

    CudaPartitioner([
        CudaBackend.generate_method_name_compile_spec("forward"),
        CompileSpec("share_weights", b"ON"),
    ])
  • When sharing, move_program_to_device records 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_weights OFF with low_memory_mode ON now raises a ValueError. Without an autotune_at_compile_time spec, 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_weights alone does not do this.

Tests

  • Unit tests: the copy is deep by default and shared when asked; with sharing, the move copies written GPU tensors only when compile-time autotune is off, with the caller's values; release frees what the move created and keeps the caller's tensors; the parking fallback skips a list with nothing parkable.
  • End-to-end with 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 after run_decompositions rebuilds the program.
  • Unit tests also cover the share_weights and low-memory conflict, and the move and compile agreeing on autotune when no spec is given.
  • Each new test fails when the code it covers is broken.
  • test_replace_int64_floordiv.py now imports the backend as executorch.backends.cuda.cuda_backend. Its old backends.cuda.cuda_backend import loaded a second CudaBackend class 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 patches CudaBackend did not see the call.
  • Ran the CUDA backend tests on an A100 with PyTorch 2.14. With 8 GiB of bfloat16 weights on the GPU, the lowering peak was 27.0 GiB by default and 19.0 GiB with share_weights.

Copilot AI balanced review requested due to automatic review settings November 11, 2026 22:59
@shoumikhin shoumikhin added module: cuda Issues related to the AOTI CUDA backend release notes: backends labels Nov 11, 2026
@pytorch-bot

pytorch-bot Bot commented Nov 11, 2026 •

Copy link
Copy Markdown

🔗 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 Failure

As of commit 0f46c7b with merge base e01c6a0 (image):

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.

@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Facebook bot. Authors need to sign the CLA before a PR can be reviewed. label Nov 11, 2026
@shoumikhin

Copy link
Copy Markdown
Contributor Author

@claude /pr-review

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.

@claude

claude Bot commented Nov 11, 2026 •

Copy link
Copy Markdown

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 autotune_at_compile_time OFF, likely writes to the caller's own buffer, and the test meant to catch that cannot fail.

Detailed review

PR Review: #24937

Summary

The PR shares state-dict tensors in CudaBackend.copy_exported_program_for_preprocess in every mode, and limits autotune parking and release_moved_tensors to the GPU tensors the move created. There are three problems:

  • Lowering likely writes buffers the caller owns, and the test for that cannot fail.
  • The release hook's new contract can only be met through a thread-local.
  • The new autotune tests never reach the _parkable check.

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

  • Default-mode lowering likely writes the caller's GPU buffers when autotune_at_compile_time is OFF (major). This is at backends/cuda/cuda_backend.py:1209-1215.

    • The buffer the graph writes is now the caller's:
      • CudaPartitioner inherits AotiPartitioner, which tags written buffers into the delegate (backends/aoti/aoti_partitioner.py:136).
      • For a buffer already on the GPU, move_to_device_pass returns the same tensor.
      • On main, the deep copy made it a copy in default mode. With the memo, it is the module's own buffer.
    • Lowering then writes to it:
      • With compile-time autotune off, AOTI first runs a Python wrapper on the graph's real constants (backends/cuda/passes/lower_offgraph_kv.py:590-592).
      • _unlift_graph clones buffers only to keep their original values for serialization (the repo's notes at cuda_backend.py:429-433 and :460-464). The kernels write to the buffer itself.
      • This contradicts "sharing immutable tensor storage" and "does not mutate the source tensors" (:1197-1200).
    • Trigger: CompileSpec("autotune_at_compile_time", b"OFF"), which examples/cuda/scripts/export_amd_pointwise.py:69 uses. A step counter doing add_(1) would be incremented, and a state buffer doing copy_(x) would be zeroed.
    • The test can't catch it: AotiBackend.preprocess passes the placeholders' fake meta["val"] to aot_compile (backends/aoti/aoti_backend.py:350-363), and Inductor turns fake inputs into zeros for that first pass. So in test_gpu_buffer_the_graph_writes_is_left_unchanged (backends/cuda/tests/test_cuda_export.py:788-810), count.add_(x) adds zeros to zeros and passes either way. Its docstring also gets the clone backwards.
    • Fix:
      1. Make the test's write independent of the input, e.g. self.count.add_(1).
      2. If the test then fails, keep deep-copying the GPU tensors named in graph_signature.buffers_to_mutate by leaving them out of tensor_memo. The weights stay shared.
      3. Low-memory mode already shared these buffers before this PR (apart from the KV caches it replaces), so the same fix covers it.

    Fix this →

API Design

  • release_moved_tensors now frees only what a thread-local snapshot of the move recorded (minor). This is at cuda_backend.py:1563-1571 and :1605-1610, and at backends/aoti/aoti_backend.py:197-202.

    • The new base-class rule can't be met from the hook's arguments. The rule says "an override must not free tensors the program already had before that move". By the time release runs, device_edge_program holds the caller's tensors and the moved ones side by side. Every backend that overrides release would need its own side channel like _MOVED_TENSORS.
    • Tensors added after the move are no longer freed. Main freed CUDA tensors that custom passes or run_decompositions add between the move and release; this PR keeps them. One example is LowerOffGraphKVPass._cell_buffer's torch.zeros(..., device=device) (lower_offgraph_kv.py:690). They are small in-tree today.
    • The docstring at :1587 isn't always true. _MOVED_TENSORS.refs is never cleared. "Without a matching move nothing is freed" holds only while the program shares no storage with the last program moved on that thread.
    • Fix: have AotiBackend.preprocess record the caller's storages before move_program_to_device and pass them to release_moved_tensors. Release then frees every CUDA tensor whose storage is not in that set. Only CudaBackend overrides release in-tree, and autotune's offload list can stay on _MOVED_TENSORS.

    Fix this →

  • Low confidence: can default mode offload the weights too? This is at cuda_backend.py:1202-1204.

    • The docstring says "Only low-memory mode lets Inductor move them to disk". But default mode just leaves aot_inductor.autotune_offload_constants_min_device_fraction unset (:1383-1387).
    • If torch's default is a positive fraction, weights that take more of the GPU than that fraction are offloaded in default mode too. That is the case this PR targets: those weights would go to disk and come back at new addresses.
    • test_gpu_weights_are_shared_with_the_compile uses 512 MiB of weights, so it can't reach that case.
    • I couldn't read the torch source here to check the default.

Testing

  • The new "nothing to park" tests never reach _parkable. Both pass offload=lambda: [], so they would also pass with a plain if not offload:. They are test_oom_with_nothing_to_park_falls_back_without_parking (backends/cuda/tests/test_cuda_graph_timing.py:111) and test_out_of_memory_with_nothing_to_park_skips_the_parked_retry (backends/cuda/tests/test_autotune_launch_params.py:141).

    • The case _parkable exists for is a non-empty list with nothing parkable. That happens in low-memory mode when the weights are the caller's: the list then holds only the zero-byte KV tensors that _move_to_device_resize_kv creates.
    • Add a case with a CUDA tensor whose storage was resized to 0.

    Fix this →

Recommendation

Request Changes

The test that should catch lowering writing the caller's buffers cannot fail. Reading the code, that write happens when autotune_at_compile_time is OFF. Before merging, make the test's write independent of the input. If the test then fails, keep copying the GPU buffers the graph writes.

@shoumikhin
shoumikhin force-pushed the cuda-preprocess-share-gpu-weights branch from 5e9fefe to 67ae9b4 Compare November 12, 2026 00:01
Copilot AI balanced review requested due to automatic review settings November 12, 2026 00:01

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.

@shoumikhin

Copy link
Copy Markdown
Contributor Author

@claude /pr-review

@claude

claude Bot commented Nov 12, 2026 •

Copy link
Copy Markdown

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 release_moved_tensors never frees them and autotune can't park them.

Detailed review

PR Review: #24937

Summary

The PR shares state-dict tensors in CudaBackend.copy_exported_program_for_preprocess, copying only GPU buffers the graph writes. It also keeps release and autotune parking away from the storages the program had before the move. The copies of written GPU buffers are counted among those storages, so they are never freed or parked (major). There are three minor problems:

  • The ownership set reaches the move and release hooks by different routes.
  • The preprocess ordering for host weights is untested.
  • Parameters the graph writes may still be shared (low confidence).

Nothing was run here, since there is no GPU. The findings come from reading the code.

Testing

  • No test checks that AotiBackend.preprocess still frees weights moved from the CPU (minor).

    • The release tests (backends/cuda/tests/test_cuda_partitioner.py:651, :681, :703) compute _tensor_storages(copied) themselves and call the hooks directly.
    • No end-to-end test checks what release frees.
    • So the ordering at backends/aoti/aoti_backend.py:326-327, which its comment says matters, is untested. If the set were taken after the move, release would free nothing for weights moved from the CPU, and every test would still pass.

    Fix this →

API Design

  • The ownership set reaches the two hooks by different routes (minor).

    • AotiBackend.preprocess computes caller_storages (aoti_backend.py:327) and passes it only to release_moved_tensors.
    • CudaBackend.move_program_to_device recomputes the same set from the same program (cuda_backend.py:1575) and applies it through the _MOVED_TENSORS thread-local.
    • The base move_program_to_device docstring (aoti_backend.py:190-195) does not state the rule. A backend implementing the hooks can only learn it from the release docstring.
    • _tensor_storages is private, but cuda_backend.py:26 and test_cuda_partitioner.py:17 import it.
    • This is also a BC break for out-of-tree backends: release_moved_tensors gains a required parameter (aoti_backend.py:203). An override with the old signature fails with TypeError at the end of preprocess, after the whole AOTI compile. The class is @experimental, but the PR is labeled release notes: backends, so the note should say this.
    • Fix: pass caller_storages to move_program_to_device too, state the rule in its docstring, drop the recomputation, and give the helper a public name.

    Fix this →

Backward Compatibility

  • Low confidence: parameters the graph writes are now shared with the caller (minor).

    • written at cuda_backend.py:1215 reads only graph_signature.buffers_to_mutate.
    • A delegated graph that writes a GPU parameter would get the caller's parameter. backends/native/serialization/graph_serialize.py:852 already reads parameters_to_mutate. Per the PR's own docstring, without compile-time autotune Inductor then writes that tensor. Main deep-copied it in default mode.
    • I did not confirm that CudaPartitioner delegates parameter writes. They are rare in inference graphs.

    Fix this →

Performance

  • The copies of written GPU buffers are counted as the caller's, so nothing frees or parks them (major).

    • Why:
      • preprocess receives the program copy_exported_program_for_preprocess returns, not the caller's (exir/backend/backend_api.py:114-121, :589-600).
      • That copy gives each written GPU buffer a new storage (cuda_backend.py:1214-1227). The move keeps that storage, because .to("cuda") returns a CUDA tensor unchanged.
      • caller_storages is taken from that copy (aoti_backend.py:327, cuda_backend.py:1575), so it holds these new storages too. _track_moved_tensors leaves them out of _MOVED_TENSORS (cuda_backend.py:630-635), and release_moved_tensors skips them (:1615).
      • On main, default mode emptied this copy at the end of preprocess, and autotune could park it.
      • The docstrings that say these storages "belong to the caller" (aoti_backend.py:211-213, cuda_backend.py:1591-1594) are wrong for them.
    • Trigger: lowering a model kept on the GPU whose graph writes a buffer, such as a static KV cache updated with index_copy_, in default mode. In low-memory mode, the same applies to any written buffer that _is_kv_buffer rejects: one whose name lacks kv_cache, or a cache that is not all zeros.
      • In a multi-method export, _lower_all_submodules_to_backend makes every method's copy up front (backend_api.py:589-600). Each method's buffer copy now stays on the GPU for the rest of the lowering, where main emptied it when its method finished. The backend notes KV caches can be 10+ GiB (cuda_backend.py:1565-1566).
      • With weights already on the GPU, these copies are the only GPU memory autotune could park, so its out-of-memory fallback now has nothing to park.
    • Tests:
      • test_program_copy_copies_gpu_buffers_the_graph_writes (test_cuda_partitioner.py:614) stops at the copy.
      • The low-memory KV exemption at cuda_backend.py:1224 has no test, because no buffer in backends/cuda/tests has kv_cache in its name.
    • Fix:
      1. Share every tensor in copy_exported_program_for_preprocess.
      2. In CudaBackend.move_program_to_device, after the move and before _track_moved_tensors, replace each written CUDA buffer whose storage is still in caller_storages with a clone.
        • The clones then count as created by the move, so they are tracked, parked and released.
        • A multi-method export then makes them one method at a time.
        • Low-memory mode already replaces KV caches with empty storage on the move, so those are skipped without extra code.
      3. Test that the clone has 0 bytes after release and the module's buffer is unchanged, in both modes. Add a low-memory case with an all-zero GPU kv_cache buffer that is not cloned.

    Fix this →

Recommendation

Request 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 move_program_to_device instead fixes that and makes the documented ownership rule true.

@shoumikhin
shoumikhin force-pushed the cuda-preprocess-share-gpu-weights branch from 67ae9b4 to 6eaab70 Compare November 12, 2026 02:14
Copilot AI balanced review requested due to automatic review settings November 12, 2026 02:14

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.

@shoumikhin

Copy link
Copy Markdown
Contributor Author

@claude /pr-review

@claude

claude Bot commented Nov 12, 2026 •

Copy link
Copy Markdown

Claude finished @shoumikhin's task in 31m 9s —— View job


Request changes: with autotune_at_compile_time OFF, the new clone in move_program_to_device turns a GPU parameter the graph writes into a plain tensor, which .module() rejects, and no test lowers such a graph end to end.

Detailed review

PR Review: #24937

Summary

The PR shares state-dict tensors with the caller in every mode of CudaBackend.copy_exported_program_for_preprocess. It also clones the GPU tensors the graph writes when compile-time autotune is off, and keeps release and autotune parking away from the storages the program had before the move. The new clone breaks lowering of a graph that writes a GPU parameter (major). There are four minor problems:

  • No test lowers a graph that writes a GPU tensor.
  • The set of storages the program had before the move is computed in two places.
  • With compile-time autotune off, the new clones can be parked while kernels read them (low confidence).
  • The autotune_at_compile_time spec is parsed twice, and the two parses disagree when the key is given twice.

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

  • Low confidence: with compile-time autotune off, the new clones can be parked while kernels read them (minor). This is at backends/cuda/cuda_backend.py:1594.

    • get_extra_aoti_compile_context_manager passes offload=_moved_program_tensors in every mode (:1503-1505, :1511-1513). With OFF, that list now holds the clones, as backends/cuda/tests/test_cuda_partitioner.py:652 asserts.
    • With OFF, Inductor runs the graph on those real tensors (the PR's comment at :1579-1580 says so). Its Triton kernels autotune there through the benchmarker that cuda_graph_timing replaces. When a timing keeps running out of GPU memory, _parked_on_cpu resizes the parked storages to 0 while it times a candidate that reads them.
    • The docstring this PR edits (backends/cuda/autotune/cuda_graph_timing.py:36-40) still says parking "is safe because AOTI autotunes on random inputs, never on the model's tensors".
    • Main already had this problem for weights moved from the CPU. I couldn't read Inductor's source here to confirm that the run on real tensors autotunes through this path.
    • Fix: pass offload=None to autotune_launch_params and cuda_graph_timing when cls._autotunes_at_compile_time(compile_specs) is False. Limit the docstring's safety claim to compile-time autotune.

    Fix this →

  • _autotunes_at_compile_time parses the autotune_at_compile_time spec a second time, and its result can disagree with the first parse (minor). This is at backends/cuda/cuda_backend.py:1539-1545.

    • get_aoti_compile_options already parses the spec (:1368-1369, :1374-1375) and keeps the last entry for the key. The new helper returns the first entry.
    • Trigger: compile specs that give the key twice, ON and then OFF. AOTI compiles with OFF, so Inductor runs the graph on the real tensors. But the move does not clone the GPU tensors the graph writes, so that run writes the caller's tensors.
    • Fix: parse the spec in one place, e.g. have get_aoti_compile_options always set options["triton.autotune_at_compile_time"] from the helper.

    Fix this →

Testing

  • No test lowers a graph that writes a GPU tensor (minor).

    • All the new end-to-end tests in backends/cuda/tests/test_cuda_export.py use _ScaleShift, which only reads its parameters. test_move_copies_gpu_tensors_the_graph_writes (test_cuda_partitioner.py:614) stops after the move and release and never compiles.
    • In default mode, this PR now relies on two things that nothing checks:
      • With compile-time autotune off, the clone keeps Inductor's run on real tensors away from the caller's tensors.
      • With it on, the compile leaves a written GPU buffer it now shares with the caller, such as a KV cache, unchanged.
    • On main, the default-mode deep copy made both hold anyway.
    • Fix: lower the State module from that test with [] and with autotune_at_compile_time=OFF, in default and low-memory mode. Run it, compare the output with eager on a separate copy of the module, and check that lowering leaves the module's count and scale unchanged. This would also have caught the crash under Backward Compatibility.

    Fix this →

API Design

  • The set of storages the program had before the move is computed in two places (minor).

    • AotiBackend.preprocess takes it at backends/aoti/aoti_backend.py:327 and passes it only to release_moved_tensors. CudaBackend.move_program_to_device computes it again at cuda_backend.py:1573 for _track_moved_tensors. Parking and release agree only while the two computations match.
    • The base move_program_to_device docstring (aoti_backend.py:190-195) doesn't say what the move may do with those storages.
    • _tensor_storages is private, but cuda_backend.py:26 and test_cuda_partitioner.py:17 import it.
    • test_release_frees_only_what_the_move_created (test_cuda_partitioner.py:696) asserts that release also frees added, which the move did not create.
    • Fix: pass the set to move_program_to_device too, state the rule in its base docstring, drop the recomputation, and give the helper a public name.

    Fix this →

Backward Compatibility

  • Cloning a GPU parameter the graph writes turns it into a plain tensor, so lowering fails (major). This is at backends/cuda/cuda_backend.py:1593.

    • Why:
      • written includes parameters_to_mutate (:1582-1585), and nn.Parameter.clone() returns a plain torch.Tensor.
      • preprocess then calls device_edge_program.module() (backends/aoti/aoti_backend.py:359). That registers each name in graph_signature.parameters as a parameter, and torch rejects a value that is not an nn.Parameter.
      • Line 580 of the same file re-wraps parameters for this reason.
    • Trigger: autotune_at_compile_time=OFF and a GPU parameter the graph writes, in default or low-memory mode. examples/cuda/scripts/export_amd_pointwise.py:69 sets OFF.
      • The State module in the PR's own test is such a case when lowered through to_backend("CudaBackend", program, specs) (exir/backend/backend_api.py:114-121).
      • On main, default mode deep-copied instead, which keeps the Parameter type.
    • The test can't catch it: test_move_copies_gpu_tensors_the_graph_writes (backends/cuda/tests/test_cuda_partitioner.py:614) checks only addresses and sizes, and never calls moved.module().
    • Fix: re-wrap the clone as line 580 does, torch.nn.Parameter(tensor.clone(), tensor.requires_grad), when the tensor is an nn.Parameter. Call moved.module() in the test.

    Fix this →

Recommendation

Request 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
  • Gather context (diff, changed files, repo guidelines)
  • Independent reviews (three reviewers)
  • Consolidate findings
  • Fact-check findings
  • Post review

The shallow checkout has no merge base with origin/main, so the diff reviewed is the PR's single commit (HEAD~1..HEAD), which matches the PR's 8 files, +364/-72.

@shoumikhin
shoumikhin force-pushed the cuda-preprocess-share-gpu-weights branch from 6eaab70 to 51302f2 Compare November 12, 2026 04:02
Copilot AI balanced review requested due to automatic review settings November 12, 2026 04:02
@shoumikhin

Copy link
Copy Markdown
Contributor Author

@claude /pr-review

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.

@claude

claude Bot commented Nov 12, 2026 •

Copy link
Copy Markdown

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 autotune_at_compile_time is OFF (low confidence), the multi-method test has no memory bound, no end-to-end test lowers with OFF, and the base hook docstrings do not state the new caller-storage contract.

Detailed review

PR Review: #24937

Summary

The PR makes CudaBackend.copy_exported_program_for_preprocess share the program's state_dict and constants tensors with the caller instead of deep-copying them, keeps the caller's GPU tensors out of the release and OOM-parking paths, and clones caller tensors the graph writes when autotune_at_compile_time is OFF. Four minor issues remain, and none blocks merging. Nothing was run on a GPU, and the torch source was not available in this checkout, so the Inductor-dependent part of the Code Quality finding is low confidence.

Code Quality

  • With autotune_at_compile_time OFF, the OOM parking fallback can free weights that a candidate reads (low confidence; the claim predates this PR, but the PR rewrote the docstring sentence that carries it). backends/cuda/autotune/cuda_graph_timing.py:36-40 and the _MOVED_TENSORS comment at backends/cuda/cuda_backend.py:615-620 say parking is safe because AOTI autotunes on random inputs. With OFF that does not hold: Inductor first runs the graph on the real constants, as the PR's own comment at cuda_backend.py:1580-1581 says (see also backends/cuda/passes/lower_offgraph_kv.py:590-592). Yet autotune_launch_params and cuda_graph_timing get offload=_moved_program_tensors in every mode (cuda_backend.py:1503-1513). If Inductor's CachingAutotuner clones only the arguments a kernel mutates, as I recall but could not check here, a candidate timed in that pass reads a weight moved from the host in place. After a second OOM, _time_capturing_robustly (cuda_graph_timing.py:266-275) and _time_candidates_within_memory (backends/cuda/autotune/launch_params.py:295-300) resize_(0) that weight and then run the candidate, which reads freed device memory; an illegal-address error there is sticky and ends the export. Pass offload=None when cls._autotunes_at_compile_time(compile_specs or []) is False (compile_specs can be None there, see :1442-1443), and limit both comments to compile-time autotune. Fix this →

Testing

  • test_methods_share_gpu_weights (backends/cuda/tests/test_cuda_export.py:786) also passes on main, so it does not guard the multi-method memory saving. lower_all_submodules_to_backend makes every method's copy before any preprocess runs (exir/backend/backend_api.py:589-600), so on main two GPU deep copies of _ScaleShift's 512 MiB of weights were alive at once. The test checks pointers, values and outputs, and a deep copy preserves all three. Add the bound _lower_gpu_weights uses: reset the peak stats and record memory_allocated() before lowering (:715-716), then assert the peak growth stays below 2 * weight_bytes (:722). Fix this →
  • No end-to-end test lowers a GPU tensor the graph writes with autotune_at_compile_time OFF, the only mode in which the clone at backends/cuda/cuda_backend.py:1579-1598 runs. test_lowering_leaves_written_gpu_buffers_unchanged (backends/cuda/tests/test_cuda_export.py:746) passes only the method-name spec, so compile-time autotune is on and the clone is skipped. test_move_copies_gpu_tensors_the_graph_writes (backends/cuda/tests/test_cuda_partitioner.py:615) covers OFF but stops after the move and release, so nothing checks that Inductor's first pass leaves the module's count untouched and packages the right value. Also run the Counter test with CompileSpec(key="autotune_at_compile_time", value=b"OFF"); without the clone, count.add_(1) in that pass would write the module's buffer. Fix this →

API Design

  • The caller-storage rule is a new contract between AotiBackend.preprocess and both hooks, but it is computed twice and stated in neither base hook (still open from the previous round).

    • preprocess takes the set before the move (backends/aoti/aoti_backend.py:326-327) but passes it only to release_moved_tensors (:439). CudaBackend.move_program_to_device recomputes it from its own argument (backends/cuda/cuda_backend.py:1574) to choose what to clone and what to track in _MOVED_TENSORS. The two sets agree only because nothing runs between aoti_backend.py:327 and the move at :331.
    • The base move_program_to_device docstring (aoti_backend.py:190-195) does not say that the program's tensors may be the caller's and must be neither written nor freed. The CudaBackend override's docstring (cuda_backend.py:1562-1571) still says non-low-memory exports "use the stock pass" and mentions neither the clone nor the tracking.
    • The base release_moved_tensors docstring (aoti_backend.py:205-206) and the comment at aoti_backend.py:435-438 say release frees what move_to_device_pass placed. The override frees every CUDA tensor whose storage is not in caller_storages, including tensors added after the move, and test_release_frees_all_but_the_caller_storages (backends/cuda/tests/test_cuda_partitioner.py:698) asserts exactly that.
    • _tensor_storages is private but imported by cuda_backend.py:26 and test_cuda_partitioner.py:17.

    Pass the set to move_program_to_device as well and drop the recomputation, state the contract in both base docstrings, and give the helper a public name. Only CudaBackend overrides either hook in-tree, and release_moved_tensors already gained a required argument in this PR, so changing the move hook's signature too costs out-of-tree overrides little more. Fix this →

Recommendation

Approve

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:

  • Gather context: PR description, the three earlier reviews, and the diff (HEAD~1..HEAD, because the shallow checkout has no merge base with origin/main)
  • Three independent reviews
  • Consolidate: about 20 candidates merged into 7
  • Fact-check: 3 dropped, 4 kept

@shoumikhin
shoumikhin force-pushed the cuda-preprocess-share-gpu-weights branch from 51302f2 to f4fc238 Compare November 12, 2026 06:07
Copilot AI balanced review requested due to automatic review settings November 12, 2026 06:07
@shoumikhin

Copy link
Copy Markdown
Contributor Author

@claude /pr-review

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.

@shoumikhin

Copy link
Copy Markdown
Contributor Author

Thanks for the reviews. Status after the new push:

  1. Written parameters lose their type. Confirmed: Parameter.clone() returns a plain tensor, and program.module() then fails. The copy is now wrapped back into nn.Parameter, as the low-memory move already does, and the unit test calls moved.module().

  2. Copies of written buffers counted as the caller's (earlier review). The preprocess copy now shares every tensor. Only when compile-time autotune is off does move_program_to_device give each written GPU buffer or parameter its own copy. It does this after the caller's storages are recorded, so release frees the copy. With compile-time autotune on, the default, nothing is copied.

  3. Tests. New end-to-end test: lower a model whose graph writes a GPU buffer, then check that the module's buffer is unchanged and the output matches eager. New unit test: preprocess records the caller's storages before the move. The two-method test now also bounds GPU memory; it fails with the old deep copy. No end-to-end test with compile-time autotune off: Inductor's first pass crashed on one in CI (torch 2.14). The unit test covers the copy and release on that path, but not the compile.

  4. Not changed:

    • Parking while compile-time autotune is off: main does the same for every tensor the move creates. I would fix it in its own PR, by not parking in that mode.
    • The storage set built in two places: both use the same helper on the same program, so they cannot disagree. Passing it into the move would change a second hook. The spec parsed twice now takes the last value in both places, and a test checks that they agree.
    • The new release_moved_tensors argument is now mentioned in the description.
  5. Default-mode offload: torch's default autotune_offload_constants_min_device_fraction is 1.0, so only low-memory mode (0.0) moves the weights.

@shoumikhin
shoumikhin force-pushed the cuda-preprocess-share-gpu-weights branch from f4fc238 to 8e45925 Compare November 16, 2026 15:28
@claude

claude Bot commented Nov 17, 2026 •

Copy link
Copy Markdown

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 autotune_at_compile_time case is decided, a duplicated tensor walk, an undocumented rule that passes must not mutate shared tensors, and two test gaps. Three of them are still open from the previous review.

Detailed review

PR Review: #24937

Summary

Before this PR, CudaBackend.copy_exported_program_for_preprocess deep-copied the caller's GPU-resident weights for every method; now it shares them. move_program_to_device, release_moved_tensors and the autotune parking path no longer write, free or park storages the caller owns. Without compile-time autotune, a caller GPU tensor that the graph writes gets its own copy.

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

  • backends/cuda/cuda_backend.py:1593-1594: with no autotune_at_compile_time spec, the move and the compile decide separately (low confidence).
    • The two decisions:
      • move_program_to_device copies the GPU tensors the graph writes only when _autotunes_at_compile_time returns False. With no spec, that function predicts how Inductor resolves None: it assumes None "turns it on for AOT compiles".
      • get_aoti_compile_options (1421-1422) leaves the option unset, so the compile uses whatever Inductor actually resolves.
    • Failure: if None resolves to the two-pass path, the move skips the copy and Inductor's first pass writes the caller's GPU buffers.
    • Coverage: test_move_and_compile_agree_on_autotune_at_compile_time has no [] case, and with no spec the key is missing from options anyway. The only guard is test_lowering_leaves_written_gpu_buffers_unchanged, and only for the torch version GPU CI runs.
    • Fix: always set options["triton.autotune_at_compile_time"] = cls._autotunes_at_compile_time(compile_specs). The move and the compile then agree by construction. Nothing changes where the prediction is right, and the agreement test can cover [].
    • Fix this →
  • backends/cuda/cuda_backend.py:1688-1699: release_moved_tensors re-implements _program_cuda_tensors.
    • _program_cuda_tensors (665-668) has one caller, _track_moved_tensors (674).
    • Release walks state_dict and constants by hand instead, with its own getattr pools and is_cuda filter.
    • Risk: if the two walks drift apart, the parking tracker and release will disagree about which tensors the move created.
    • Fix: loop over _program_cuda_tensors(device_edge_program) in release. This removes the duplicate walk and gives the helper a second caller.
    • Fix this →

Testing

  • No test covers a caller GPU tensor stored in constants.
    • _tensor_storages, _program_cuda_tensors and release_moved_tensors all read constants as well as state_dict. But every caller-owned GPU tensor in the new tests is a parameter or a persistent buffer.
    • In test_release_frees_all_but_the_caller_storages (backends/cuda/tests/test_cuda_partitioner.py:700-720), the only constants entry is added. It is inserted after the move to check that it is freed.
    • Failure: if constants dropped out of _tensor_storages, a caller's non-persistent GPU buffer would be freed at the end of preprocess. A RoPE table is an example of such a buffer. It could also be parked when autotune runs out of memory. No test would fail.
    • Fix: register a GPU buffer with persistent=False in that test, and assert that it keeps its bytes and values after release.
    • Fix this →
  • backends/cuda/tests/test_cuda_partitioner.py:653-655: the test never checks the copies' values.
    • test_move_copies_gpu_tensors_the_graph_writes only asserts that each copy has a new data_ptr and is tracked.
    • Failure: a copy that does not hold the caller's values would pass, for example one made with empty_like. The compiled program would then start from wrong buffer and parameter values.
    • Fix: add self.assertTrue(torch.equal(tensor, value)) to that loop, before release.
    • Fix this →

API Design

  • The rule that shared tensors are never written is only in the copy_exported_program_for_preprocess docstring (backends/cuda/cuda_backend.py:1238-1252).
    • What changed: after this PR, the program preprocess gives to move_program_to_device holds the caller's GPU storages, not copies. So does the program it then gives to every custom pass (backends/aoti/aoti_backend.py:340-346). Passes with requires_exported_program get the whole program.
    • Missing docs: none of these docstrings mention it:
      • AotiBackend.get_custom_passes (aoti_backend.py:125-127)
      • CudaBackend.get_custom_passes (cuda_backend.py:1308-1315)
      • the base move_program_to_device (aoti_backend.py:190-195)
    • Failure: a pass or override that updates a weight or buffer in place now silently changes the user's eager model and every other method that shares the tensor. Folding a scale into a weight or quantizing in place are examples. Before this PR, such a pass changed a private copy. For CudaBackend subclasses that have such passes, this is also a behavior change.
    • Fix: add one sentence to the base get_custom_passes and move_program_to_device docstrings, like the caller_storages note already added to release_moved_tensors. It should say that tensors in state_dict/constants may be the caller's, so entries must be replaced, never mutated in place.
    • Related: cuda_backend.py:1622 ("Low-memory methods share their CPU weights, …") now reads as if only low-memory methods share weights. Every mode does now.
    • Fix this →

Recommendation

Approve

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
  • Gather context: read the PR description and discussion, and the diff HEAD~2..HEAD (8 files, +451/−85). The shallow checkout has no merge base with origin/main.
  • Independent reviews: 3 blind reviewers covered all 8 changed files.
  • Consolidate: merged about 30 candidates into 14 distinct findings.
  • Fact-check: re-read the cited code for each finding. Kept 5 and dropped 9:
    • parking with compile-time autotune off: a documented limitation the author deferred;
    • points the author already answered in the discussion;
    • pre-existing issues: _is_low_memory_mode uses the first spec, the example_inputs copy, test placement;
    • intended behavior: in low-memory mode, weights come back at new addresses;
    • unrealistic or only suspected triggers: clone() aliasing, storage access outside the try;
    • justified choices: the _TORCH_CAN_OFFLOAD skip, the single-method memory margin;
    • nits outside the requested scope: stale launch_params docstrings, the private _tensor_storages import.
  • Post the review

@Gasoonjia

Copy link
Copy Markdown
Contributor

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 risky

Before 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 signature

caller_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;
the release_moved_tensors hook signature stays the same;
if a tensor is ever missing from the set, we keep memory we could have freed (safe). With the current approach, a missing entry means we free or park the caller's tensor (unsafe).

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.

@shoumikhin
shoumikhin force-pushed the cuda-preprocess-share-gpu-weights branch from d1f31a8 to eb3aa01 Compare November 19, 2026 00:05
@shoumikhin shoumikhin changed the title CUDA backend: share GPU-resident weights in preprocess instead of deep-copying them CUDA backend: add a share_weights option, and stop low-memory mode from freeing GPU weights Nov 19, 2026
Copilot AI balanced review requested due to automatic review settings November 19, 2026 00:05

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.

@shoumikhin

Copy link
Copy Markdown
Contributor Author

Sharing tensors by default feels risky

Fair point. Sharing is opt-in now, and the default is the deep copy again, same as main.

Is it that low-memory mode has costs you want to avoid here [...] a separate spec that only turns on tensor sharing

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 share_weights spec that only turns on sharing. low_memory_mode still shares too. On an A100 with 8 GiB of bf16 weights on the GPU, the lowering peak is 27.0 GiB by default (same as main) and 19.0 GiB with share_weights.

The guards are still needed either way: on main, low_memory_mode empties the caller's GPU weights at the end of preprocess (I measured 0 bytes left after export).

If we do keep sharing as the default, I'd like a cheap guard against regressions

Since sharing is opt-in now, I left the assert out. _version would also be noisy here, because export itself bumps it on a buffer the graph writes. The tests compare the caller's tensors before and after export instead.

Track what the move created instead of what the caller owns, and keep the hook signature

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. aoti_backend.py and the release_moved_tensors signature are back to main.

Longer term: does compilation need real weights at all?

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.

@shoumikhin

Copy link
Copy Markdown
Contributor Author

@claude review

@claude

claude Bot commented Nov 19, 2026 •

Copy link
Copy Markdown

Claude finished @shoumikhin's task in 5m 6s —— View job


Approve: nothing blocks merging. Two minor issues remain: low_memory_mode silently overrides an explicit share_weights=OFF, and when no autotune_at_compile_time spec is given, the copy decision still depends on a guess about Inductor's default (low confidence).

Detailed review

PR Review: #24937

Summary

The PR adds an opt-in share_weights compile spec that skips the preprocess deep copy. When sharing is on, either through share_weights or low_memory_mode, release and autotune parking act only on the CUDA tensors that move_program_to_device created, and when compile-time autotune is off the move copies the GPU tensors the graph writes. Two minor issues remain. Nothing was run here: there is no GPU, and the installed torch source couldn't be read.

API Design

  • low_memory_mode overrides share_weights without saying so, and the two specs are parsed by different rules (minor). This is at backends/cuda/cuda_backend.py:1601-1609.

    • _shares_weights returns True as soon as _is_low_memory_mode is true, before it reads share_weights. So [low_memory_mode=ON, share_weights=OFF] still shares, with no error or warning. An invalid value such as share_weights=b"yes" is only rejected when low-memory mode is off.
    • _is_low_memory_mode (:1594-1599) takes the first low_memory_mode spec and never raises. share_weights and autotune_at_compile_time take the last spec and raise on anything but ON/OFF. Before this PR, that mismatch only affected the compile. Now it also decides whether the caller's GPU tensors are kept or freed.
    • The new paragraph in docs/source/backends/cuda/cuda-overview.md:112 says low-memory mode "shares them too". It doesn't say that share_weights=OFF is ignored there, and no test covers that combination.
    • Fix: in _shares_weights, validate share_weights first and raise when it is explicitly OFF together with low-memory mode. Or say in the docs that low-memory mode always shares. Add a test for the combination.

    Fix this →

Code Quality

  • Low confidence: with no autotune_at_compile_time spec, the move and the compile still decide separately (minor; raised in an earlier round and not answered). This is at backends/cuda/cuda_backend.py:1611-1618.

    • _autotunes_at_compile_time falls back to torch._inductor.config.triton.autotune_at_compile_time is not False, which assumes Inductor treats None as ON for AOT. get_aoti_compile_options leaves the option unset, so the compile uses whatever Inductor actually resolves.
    • Trigger: share_weights=ON with no autotune spec, on a torch build or Inductor config where None resolves to the run on real tensors. The move then skips the copy, and Inductor's first pass writes the caller's GPU buffers.
    • test_move_and_compile_agree_on_autotune_at_compile_time covers only explicit specs, so this is the one case it doesn't check.
    • Fix: always set options["triton.autotune_at_compile_time"] = cls._autotunes_at_compile_time(compile_specs), so both use the same value by construction, and add [] to that test.

    Fix this →

Recommendation

Approve

Neither finding blocks merging, and both only matter when sharing is on, which is now opt-in.

Review steps
  • Gather context: the diff is HEAD~3..HEAD (8 files, +443/−95), because the shallow checkout has no merge base with origin/main
  • Three independent reviews, covering all 8 changed files
  • Consolidate: about 25 candidates merged into 9
  • Fact-check: kept 2 and dropped 7:
    • Already answered or deferred by the author: parking while compile-time autotune is off, which all three reviewers flagged; the e2e test of written GPU buffers running only with autotune on.
    • By design: release in sharing mode keeps CUDA tensors created after the move. This was the reviewer-requested "missing → kept" trade-off, and in-tree those tensors are small or 0-byte (lower_offgraph_kv.py:589-594, :690).
    • Not a defect: the docs wording, which already notes that low-memory mode moves the weights; the stale-looking release docstring, which the new sentence qualifies; GPU clones of written buffers in low-memory mode with autotune off, which are needed for correctness.
    • Weak: how the multi-method memory test depends on backend_api copying every method's program up front.

@shoumikhin
shoumikhin force-pushed the cuda-preprocess-share-gpu-weights branch from eb3aa01 to 4c6d9db Compare November 19, 2026 06:39
Copilot AI balanced review requested due to automatic review settings November 19, 2026 06:39
@shoumikhin

Copy link
Copy Markdown
Contributor Author

@claude review

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.

@claude

claude Bot commented Nov 19, 2026 •

Copy link
Copy Markdown

Claude finished @shoumikhin's task in 4m 57s —— View job


Approve: nothing blocks merging. Three minor issues remain: when no autotune_at_compile_time spec is given, whether share_weights copies written buffers still rests on a guess about Inductor's default (low confidence, raised twice and not yet answered); low_memory_mode silently overrides share_weights=OFF; and the new docs paragraph leaves out that written GPU buffers are still copied when compile-time autotune is off.

Detailed review

PR Review: #24937

Summary

The PR adds an opt-in share_weights compile spec. When sharing is on, either through share_weights or low_memory_mode, release and autotune parking act only on the CUDA tensors that move_program_to_device created. With compile-time autotune off, the move also copies the GPU tensors the graph writes. Three minor issues remain.

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

  • Low confidence: with no autotune_at_compile_time spec, the move and the compile decide separately whether Inductor runs on real tensors (minor; raised in the last two rounds and still open). This is at backends/cuda/cuda_backend.py:1617-1618 and :1435-1436.

    • The two decisions:
      • With no spec, _autotunes_at_compile_time returns config.triton.autotune_at_compile_time is not False. That assumes Inductor always treats None as ON for AOT.
      • get_aoti_compile_options leaves the option unset, so the compile uses whatever Inductor actually resolves.
    • Why this matters more now: the copy of written GPU tensors (:1674-1693) is the only thing between share_weights=ON and Inductor writing the caller's buffers. That copy depends on the guess.
    • Trigger: share_weights=ON, no autotune spec, a GPU buffer the graph writes, and an Inductor build or global config where None resolves to the run on real tensors. Two reviewers independently suspected that triton.autotune_with_sample_inputs affects how None is resolved; this was not checked.
    • Test gap: test_move_and_compile_agree_on_autotune_at_compile_time (backends/cuda/tests/test_cuda_export.py:161) covers only explicit specs. With [], the key isn't in options, so the test can't express that case.
    • Fix: always set options["triton.autotune_at_compile_time"] = cls._autotunes_at_compile_time(compile_specs). Then both use one value by construction, and the test can cover [].

    Fix this →

API Design

  • low_memory_mode overrides an explicit share_weights=OFF without saying so (minor; raised last round, unchanged). This is at backends/cuda/cuda_backend.py:1602-1609.

    • _shares_weights returns True as soon as _is_low_memory_mode is true, before it reads share_weights. So [low_memory_mode=ON, share_weights=OFF] shares anyway, and an invalid value like share_weights=b"yes" is only rejected when low-memory mode is off.
    • The two specs also use different parse rules. _is_low_memory_mode (:1594-1599) takes the first spec and never raises. share_weights takes the last spec and validates it. This now decides whether the caller's GPU tensors are kept or freed.
    • Fix: parse and validate share_weights first, and raise when it is OFF together with low-memory mode. Or state in docs/source/backends/cuda/cuda-overview.md:112 that low-memory mode always shares.

    Fix this →

  • The new docs paragraph doesn't say that written GPU tensors are still copied when compile-time autotune is off (minor). This is at docs/source/backends/cuda/cuda-overview.md:112.

    • With share_weights=ON and autotune_at_compile_time=OFF, move_program_to_device clones every caller GPU buffer or parameter the graph writes (cuda_backend.py:1674-1693).
    • For a static KV cache already on the GPU, the whole cache is duplicated. Low-memory mode avoids that because _move_to_device_resize_kv empties the cache first, but share_weights alone does not.
    • The paragraph says only that lowering "use[s] the weights where they are", so a user who sets OFF expecting the memory saving will see a peak that includes every written buffer.
    • Fix: add one sentence saying that with autotune_at_compile_time OFF, the GPU buffers the graph writes are still copied.

    Fix this →

Recommendation

Approve

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 get_aoti_compile_options always set the option resolves it in one line.

Review steps
  • Gather context: the PR description, the discussion with @Gasoonjia, and the diff HEAD~4..HEAD (10 files, +448/−98). The shallow checkout has no merge base with origin/main.
  • Three independent reviews, covering all 10 changed files
  • Consolidate: about 28 candidates merged into 9
  • Fact-check: kept 3 and dropped 6:
    • By design (requested by the maintainer): release under sharing keeps CUDA tensors added after the move, and it reads the move's thread-local record instead of its argument. "Missing → kept" was the requested trade-off, and in-tree those tensors are small (lower_offgraph_kv.py:690).
    • Intended: in low-memory mode, autotune OOM parking no longer parks the caller's GPU weights. Parking them was the bug the PR fixes.
    • Deferred by the author: parking while compile-time autotune is off; no end-to-end test of the autotune-OFF path.
    • Weak: the per-name clone splitting tied written buffers (no realistic trigger found); the getattr inconsistency between _tensor_storages and _program_cuda_tensors.

@Gasoonjia

Copy link
Copy Markdown
Contributor

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.
@shoumikhin
shoumikhin force-pushed the cuda-preprocess-share-gpu-weights branch from 4c6d9db to 0f46c7b Compare November 21, 2026 00:33
Copilot AI balanced review requested due to automatic review settings November 21, 2026 00:33

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.

@shoumikhin

Copy link
Copy Markdown
Contributor Author

@claude review effort=max

@claude

claude Bot commented Nov 21, 2026 •

Copy link
Copy Markdown

Claude finished @shoumikhin's task in 42m 25s —— View job


Approve, with minor findings. The main one: every CUDA export now forces triton.autotune_at_compile_time, including exports that don't share weights. The rest are small gaps in the API, docs and tests, plus weights that low-memory mode can no longer park.

Detailed review

PR Review: #24937

Summary

The PR adds a share_weights compile spec that lets preprocess use the caller's tensors instead of deep-copying them. It also stops low-memory mode from freeing or parking the GPU weights it shares with the caller. Nothing here blocks merging. Fix the Backward Compatibility finding first.

Backward Compatibility

  • backends/cuda/cuda_backend.py:1609-1613 — get_aoti_compile_options now always sets triton.autotune_at_compile_time. When no spec gives it, the value is a guess at Inductor's default (1804-1805). On main the option was set only when a spec asked for it (e01c6a0:1584-1585).

    • The move reads the value only when it shares tensors (1861, if shared and ...). So on the default path, which doesn't share, forcing the value buys nothing.
    • It still replaces Inductor's own handling of None on every CUDA export. If Inductor resolves None to anything other than on for some compile, those default exports change without warning. This part is low confidence: I couldn't read the torch source in this job.
    • The test meant to guard this, backends/cuda/tests/test_cuda_export.py:164-173, compares the option with _autotunes_at_compile_time(specs), the same function that sets it. It passes whatever that function returns, so it can't catch a wrong guess, and it never checks that [] gives True.

    Fix: set the option only when an autotune_at_compile_time spec is given or _shares_weights(compile_specs) is true. That keeps the agreement 0f46c7b added in the one place the move needs it. Then assert concrete values in the test. Fix this →

API Design

  • backends/cuda/cuda_backend.py:1905-1909 — When sharing, release_moved_tensors ignores device_edge_program. It frees whatever the last move_program_to_device on this thread recorded, and the refs are never cleared afterwards. Its docstring (1891-1895) says it frees the given program's tensors.

    • Trigger: move program A, move program B, then release A. That frees B's tensors and leaves A's on the GPU.
    • AotiBackend.preprocess moves and releases one program at a time (backends/aoti/aoti_backend.py:316, 424), so nothing hits this today. The override still does something other than what its signature and docstring say.

    Fix, keeping the signature: free only the tensors of _program_cuda_tensors(device_edge_program) whose storage belongs to a tensor in _moved_program_tensors(). Fix this →

  • backends/cuda/cuda_backend.py:1772-1778 — _is_low_memory_mode takes the first low_memory_mode spec and doesn't validate it. get_extra_aoti_compile_context_manager takes the last one and validates it (1686-1693). This predates the PR, but the new share_weights=OFF error (1787-1793) depends on it:

    • [low_memory_mode=OFF, low_memory_mode=ON, share_weights=OFF] raises nothing and makes a deep copy. The compile still runs in the low-memory context.
    • [low_memory_mode=ON, low_memory_mode=OFF, share_weights=OFF] raises, even though the compile treats the mode as OFF.

    Fix: read every spec with _on_off_compile_spec_value(spec) so the last one wins, as _shares_weights and _autotunes_at_compile_time already do. All four callers (1360, 1623, 1787, 1848) want that answer. Fix this →

  • docs/source/backends/cuda/cuda-overview.md:112 has two errors:

    • "about twice their size" holds only for one method with one partition. exir/backend/backend_api.py:589-600 makes every method's and partition's copy before the first preprocess, so N methods need about N+1 times the weights. The PR's own comment at test_cuda_export.py:998-999 says this. Multi-method exports are also where the option saves the most.
    • "the GPU buffers and parameters that the graph writes, such as a KV cache, are still copied" is wrong in low-memory mode. There _move_to_device_resize_kv replaces an all-zero kv_cache buffer with an empty placeholder (cuda_backend.py:745-746, 752-754), so it takes no GPU memory.

    Fix this →

Testing

  • backends/cuda/tests/test_cuda_partitioner.py:631-680 — test_sharing_move_copies_gpu_tensors_the_graph_writes is the only test that shares weights with compile-time autotune off. Its State has only tensors the graph writes, and all of them are in state_dict. The suite still passes after either of these edits to cuda_backend.py:

    • deleting the name in written check (1872), which makes every shared GPU tensor a copy;
    • dropping moved._constants from the loop (1869).

    Fix: add a GPU Parameter that the graph only reads, and a written persistent=False buffer, which lands in constants. Assert that the read-only Parameter keeps the caller's data_ptr() and is not in _moved_program_tensors(). Assert that the non-persistent buffer is copied. Fix this →

  • backends/cuda/tests/test_cuda_export.py:909-934 and 1010-1031 — Neither test checks the part of its docstring that is specific to this PR:

    • test_sharing_leaves_written_gpu_buffers_unchanged: module.count stays zero and the output matches whether or not the compile shares count. The test would keep passing if share_weights stopped sharing.
    • test_sharing_frees_weights_moved_from_the_host: the docstring says release also works after run_decompositions rebuilds the program, but nothing asserts that a rebuild happened.

    Fix: record the program move_program_to_device returns. In the first test, assert that its count has module.count.data_ptr(). In the second, assert that the program passed to release_moved_tensors is a different object. Fix this →

Performance

  • backends/cuda/cuda_backend.py:844-849 — In low-memory mode, weights the caller already keeps on the GPU are no longer parked when an autotune timing runs out of memory. On main, _track_moved_tensors tracked every CUDA tensor of the moved program, the caller's included (e01c6a0:823-828). Now shared storages are left out.

    • The matmul and convolution template search keeps the weights on the GPU (cuda-overview.md:109), so an out-of-memory timing there now has nothing to park.
    • The CUDA-graph timing then falls back to Inductor's default timing (autotune/cuda_graph_timing.py:268-270, 305-313).
    • The launch-param timing takes candidates[0] and logs a warning (autotune/launch_params.py:295-312).
    • These are exactly the models low-memory mode is for.

    A restore that fails (ParkedTensorsNotRestored) would leave the caller's weights empty, so leaving them out may be intended. If so, the docs should say so. Fix: state in cuda-overview.md:105-112 that weights already on the GPU are never parked. Alternatively, as main did, keep them parkable (but never releasable) in low-memory mode when compile-time autotune is on. Fix this →

Recommendation

Approve. Nothing here blocks merging. I'd still limit the triton.autotune_at_compile_time override to exports that share weights before merging, because today it also reaches exports that never opted in. The rest can be follow-ups.

Review steps
  • Diffed against e01c6a0, the PR's merge base, because the checkout is shallow and origin/main has no merge base here: 10 files, +479/−106, 5 commits.
  • Three independent reviewers covered all 10 changed files. Each wrote up its own findings.
  • Merged about 28 candidate findings into 11.
  • Checked each one against the code: kept 7 and dropped 3. All three reviewers reported the autotune override, the release scope and the docs errors. The dropped ones:
    • Missing is_fbcode() guard in _execute: three tests that were already on main (now test_cuda_export.py:881, 1489, 1577) also run executorch.runtime without one, so the new tests match the rest of the file.
    • Storage reads on the default release path: main's release already read the storage of every CUDA tensor.
    • Strides and aliasing of the clone() copy: it behaves like the v.to(location) the move already uses (preserve_format).
    • Dropped earlier, while merging candidates: comment-wording nits, and narrowing the release scope further, a direction already discussed in review.
  • Not done: nothing was run. This job has no GPU and can't read the torch source, so how Inductor resolves autotune_at_compile_time=None was not checked.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

CLA Signed This label is managed by the Facebook bot. Authors need to sign the CLA before a PR can be reviewed. module: cuda Issues related to the AOTI CUDA backend release notes: backends

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants