Skip to content

Share mutable buffers between methods in device memory - #25425

Open
shoumikhin wants to merge 8 commits into
pytorch:mainfrom
shoumikhin:share-device-mutable-buffers
Open

shoumikhin wants to merge 8 commits into
pytorch:mainfrom
shoumikhin:share-device-mutable-buffers

Conversation

@shoumikhin

@shoumikhin shoumikhin commented Nov 22, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Methods can share state, like a KV cache. MemoryPlanningPass(share_mutable_buffers=True) plans
it once, but only in host memory, and runtimes give a method with device memory its own copy.

This change fixes that:

  1. A planning pass can be reused. All methods that use shared state must use the same one.
  2. A method planned for sharing that never touches shared state drops it as an input.
  3. Each method that uses shared state marks it in a new optional field,
    ExecutionPlan.shared_non_const_buffers.
  4. Program::initialize_planned_buffer() initializes a planned buffer once.
  5. Module and the Python runtime give every method that marks a buffer one allocation of it, in
    host or device memory. A runner that plans its own memory must do the same.
  6. Layouts that older runtimes would run wrongly get version 1, which runtimes 1.5.0 to 1.6 refuse
    and older ones do not check. Older runtimes still load other shared host state, but a late load
    resets it and a method without initial data reads zeros.
  7. Export can plan the shared state in device memory, on one device. Planning adds no copies, so
    export allows only a delegate on that device, et_copy copies, metadata reads and the
    write-back to use it.

Behavior changes, for programs exported with share_mutable_buffers:

  • Module, _load_for_executorch and the Python program API share marked state between methods.
    Loading a method no longer resets it unless the caller passes its own memory. An output that
    aliases it can change when another method runs.
  • With do_quant_fusion_and_const_prop, shared state, such as an embedding's zero point, is no
    longer folded into a constant. Constant propagation run before to_executorch needs the new
    mutable_buffers argument.
  • share_memory_arenas loads marked device programs, and skip_h2d_for_constants works for a
    buffer that no method changes.
  • Export refuses programs that read stale or wrong state: a delegate copy of shared state; a host
    read of a buffer a delegate changes in its own copy; a method planned without sharing that
    uses it; 2 sharing passes; a shared buffer whose layout or initial data differ between methods;
    a control flow branch tensor on top of shared state; and a copy into a shared buffer with a
    TensorSpec of its own.

Test plan

Built from source on Linux x86_64. New tests cover export, serialization, Module and the Python
runtime; each fails without its fix. CUDA tests ran on an NVIDIA GPU; CI jobs without CUDA skip
them. Arm checks ran without the Arm tester.

Copilot AI balanced review requested due to automatic review settings November 22, 2026 02:19
@pytorch-bot

pytorch-bot Bot commented Nov 22, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

🧪 See artifacts and rendered test results at hud.pytorch.org/pr/pytorch/executorch/25425

Note: Links to docs will display an error until the docs builds have been completed.

❌ 1 New Failure, 3 Unrelated Failures, 1 Unclassified Failure

As of commit 7899155 with merge base d811540 (image):

NEW FAILURE - The following job has failed:

UNCLASSIFIED FAILURE - DrCI could not classify the following job because the workflow did not run on the merge base. The failure may be pre-existing on trunk or introduced by this PR:

FLAKY - The following jobs failed but were likely due to flakiness present on trunk:

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.

@shoumikhin shoumikhin added the release notes: exir Changes to any dialects and passes on these dialects, such as memory planning label Nov 22, 2026
@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 22, 2026

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.

@github-actions github-actions Bot added ciflow/trunk module: arm Issues related to arm backend labels Nov 22, 2026
@shoumikhin

Copy link
Copy Markdown
Contributor Author

@claude review effort=max

@claude

claude Bot commented Nov 22, 2026 •

Copy link
Copy Markdown

Claude finished @shoumikhin's task in 53m 15s —— View job


PR Review: #25425

Request Changes. With do_quant_fusion_and_const_prop=True, which both the LLM builder and the Voxtral TTS export set, constant_prop_pass still treats a shared buffer as a constant in any sharing method that only reads it, so that method silently keeps returning the initial value. The rules for owning a shared buffer at runtime, the scope of device sharing and the version check also need discussion.

Detailed review

Summary

Mutable buffers that several methods share can now live in device memory:

  • Export marks the shared arena in the new ExecutionPlan.shared_non_const_buffers and stamps v1 only when it is needed.
  • At runtime, Module and pybindings give every method that marks the arena one allocation. Program::initialize_planned_buffer initializes it once, and HierarchicalAllocator::set_initialized_buffers stops later loads from initializing it again.

Verdict: the review found:

  • one exporter bug that silently produces wrong results;
  • a new GPU test that no CI job runs;
  • rules for owning a shared buffer that core load_method neither documents nor enforces;
  • a few smaller items.

Not fully reviewed:

  • most new test bodies in exir/tests/test_memory_planning.py (+938) and extension/pybindings/test/test_pybindings.py;
  • the generated exir/_serialize/generated/executorch_flatbuffer/ExecutionPlan.py;
  • exir/banked_memory_planning.py and exir/passes/propagate_device_pass.py (skimmed only);
  • test/end2end/exported_module.py and test/models/export_program.py;
  • the BUCK, targets.bzl and CMakeLists.txt changes.

Code Quality

  • New dynamic getattr calls, and pass state reset from outside the pass.

    • exir/program/_program.py:1865, :1871, :1959 and :2004 all use getattr(p, "share_mutable_buffers", False).
    • :1928, in the same function, checks isinstance(memory_planning_pass, MemoryPlanningPass) instead.
    • :1929 then assigns a private _MemoryPlanningState() into the pass from outside it.

    Use isinstance(p, MemoryPlanningPass) and p.share_mutable_buffers throughout, and add a public reset() to MemoryPlanningPass. CLAUDE.md asks for explicit state and no dynamic getattr. Fix this →

  • _remove_unused_buffers (_program.py:281-296) re-implements exir/passes/remove_unused_parameters_pass.py. It repeats that pass's steps: copy the signature, erase the placeholder, set _graph_signature and recompile. Unlike that pass (:38), it leaves the removed buffer's entry in state_dict/constants. Generalize the existing pass to take buffers and an FQN filter, and call it here. Minor. Fix this →

Infrastructure

  • Must fix: const-prop freezes a shared buffer in a method that only reads it, and nothing reports it. How it happens:

    1. _program.py:1874-1878 computes shared but never passes it to const-prop.
    2. quant_fusion_and_const_prop_pass runs per method at :1934-1940.
    3. is_constant_buffer (exir/passes/constant_prop_pass.py:104-111) checks only that method's own buffers_to_mutate. So in a method that reads a shared buffer without writing it, get_constant_placeholder_dict (:114-139) gives const-prop the buffer's initial tensor.
    4. Const-prop then folds every op whose only tensor inputs are that buffer and constants. Examples are a slice, transpose, cast or dequant that a decoder applies to a cache another method fills, or return self.state * 2 in a getter.
    5. Once every read is folded, _remove_unused_buffers(program, shared) at :1959-1960 deletes the placeholder.

    The method then passes every refusal and never marks the shared arena. At runtime it keeps returning the initial value whatever the other methods write.

    extension/llm/export/builder.py:568-572 and examples/models/voxtral_tts/export_voxtral_tts.py:524-529 both combine do_quant_fusion_and_const_prop=True with share_mutable_buffers. The folding already happened with host sharing before this PR. But this PR adds refusals whose stated reason is that a method "would never see the changes" (_program.py:1880-1925), and it makes Module and pybindings honour the marker by default, so that guarantee should hold here too.

    Fix: pass shared through quant_fusion_and_const_prop_pass into constant_prop_pass, so that those buffers are never treated as constants. Add a regression test that exports with do_quant_fusion_and_const_prop=True, has one method write the state and another return self.state * 2, and checks that the reader sees the write. (Traced through the code; not executed.) Fix this →

  • test_methods_share_device_state (extension/pybindings/test/test_pybindings.py:4516) runs in no CI job.

    • It skips unless the CUDA backend and a GPU are both present.
    • The only job that has both runs a fixed python -m unittest list (.github/workflows/cuda.yml:589-592). That list includes test_device_planned_method_allocates_on_the_device and test_unplanned_device_output_is_device_memory, but not this test. This PR does not change cuda.yml.
    • So CI never exercises the success path of pybindings' claim_shared_buffer (pybindings.cpp:5745-5788), which allocates device memory and initializes it through initialize_planned_buffer.

    Add the test to that list. The job already fails when a listed test is skipped. Fix this →

Testing

  • extension/pybindings/test/test_pybindings.py:4445: test_invalid_method_does_not_abort_loading_shared_state only asserts assertRaises(RuntimeError), so it also passes when forward fails for an unrelated reason. Check the message as :4463 does: assertRaisesRegex(RuntimeError, "Failed to initialize shared buffer"). Fix this →
  • No Module test covers load_method(name, planned_memory) on a program with a marked buffer. That is the path extension/module/module.h:304-307 documents, but every new test in module_test.cpp lets Module allocate. A caller-supplied planned_memory skips make_planned_memory, so it gets neither the shared allocation nor set_initialized_buffers. Add a test for whatever behaviour is intended (see the first API Design item).
  • The documented torch.cond refusal for a device-shared buffer has no test. The docs (docs/source/backends/cuda/cuda-overview.md:283-285) say torch.cond cannot take the buffer. Only the catch-all "uses it on the host" in _misuse (exir/passes/memory_planning_pass.py:256) enforces this. The only torch.cond test, update_in_cond (exir/tests/test_memory_planning.py:1309-1311), passes x rather than the buffer.

API Design

  • The rules for owning a shared buffer are documented in one place only, and two runtimes each implement them separately. For a shared buffer with stored initial data, the owner must:

    1. allocate it at the largest size any method needs;
    2. call Program::initialize_planned_buffer once for every method that marks it;
    3. call set_initialized_buffers in every method's allocator before load_method.

    Only runtime/executor/program.h:176-183 says this. MethodMeta::memory_planned_buffer_is_shared (method_meta.h:273-277), Program::load_method (program.h:150-151) and module.h:304-307 only say "the same memory". A runner that follows those docs skips step 3. Then every load_method after the state has changed copies the initial data back in, and nothing reports it.

    Module (module.cpp:412-479) and pybindings (pybindings.cpp:5745-5831) each implement the rules and have already drifted apart:

    • Module visits methods in method_names() order, which comes from an unordered_set. Pybindings uses program order.
    • Their error strings differ: "shared buffer" versus "shared planned buffer".

    Consider one core helper that both runtimes and custom runners call, which initializes a caller-provided Span/Device from every marking method. For example: Program::initialize_shared_buffer(index, Span<uint8_t>, Device, const NamedDataMap*). At minimum, document all three steps on memory_planned_buffer_is_shared and in module.h. Fix this →

  • initialize_planned_buffer takes a whole HierarchicalAllocator but uses only one of its buffers. As a result:

    • Both callers build a throwaway allocator with index + 1 spans and placeholder CPU devices (module.cpp:464-471, pybindings.cpp:5768-5775).
    • It dereferences planned_memory with no null check (program.cpp:555). The helpers it reuses do check: getMemPlannedPtr (tensor_parser_exec_aten.cpp:168-171) and getTensorDataPtr (:272-277) both return InvalidState for a null allocator.

    A signature such as (method_name, buffer_index, Span<uint8_t>, Device, const NamedDataMap*) fixes both. At minimum, add the null check. Fix this →

  • set_initialized_buffers (runtime/core/hierarchical_allocator.h:127-147) is a setter called after construction, and the tensor parser reads it as a side channel. getTensorDataPtr reads it through isPlannedBufferInitialized (tensor_parser_exec_aten.cpp:216-222, used at :323 and :361). This puts load-time policy on a memory provider, and an allocator that never got the call silently initializes the buffer again. The per-buffer devices, by contrast, are a constructor argument (:50-60). Either make it a constructor parameter next to planned_buffer_devices, or pass it to load_method/MemoryManager, where the policy actually applies. (Needs discussion.)

  • Device sharing has no supported way to produce it. cuda-overview.md:275-294 tells users to:

    • subclass MemoryPlanningPass;
    • set spec.device on every placeholder;
    • remove the _h2d_copy that PropagateDevicePass adds;
    • give copies the buffer's own TensorSpec.

    The same page says "The CUDA partitioner does not do this". The only in-tree implementation is test code: BuffersOnDevicePlanningPass (exir/backend/test/device_util.py:126), which imports the private _copy_output_spec and _replace_spec (:35-38). Ship a supported opt-in, such as a public pass or a MemoryPlanningPass option, or move device sharing to a follow-up PR that includes one. (Needs discussion.)

  • Question: shared state lives as long as the Module or Program, and unloading a method keeps it (module.h:295-301, :330-331; pybindings.cpp:5727-5729). Is there meant to be a way to reset it to its initial data, or release it, without reloading the program?

Backward Compatibility

  • The version check stops protecting a custom runner once it is rebuilt against this runtime.

    • exir/version.py:25-31 bumps files that use shared_non_const_buffers to v1, because "runtimes that ignore the field would run some of these programs wrongly".
    • kMaxSupportedSchemaVersion = 1 (program.h:85) now lets every Program::load accept v1.
    • Core load_method still ignores the marker.

    A custom C++ runner that loads several methods with its own allocators is exactly a runtime that ignores the field. It either gives each method its own copy, or rewinds the state when a method loads late. After a rebuild it passes the version check, and nothing reports the problem. Consider having load_method log, or return NotSupported, when a method marks a buffer that its allocator does not flag in initialized_buffers(). (Needs discussion: refusing would also block a runner that loads only one method, which works correctly today.)

  • EXECUTORCH_SCHEMA_VERSION changed both meaning and value. It used to be the version stamped into every PTE, with value 0 (HEAD~8:exir/version.py:17, used by the emitter at HEAD~8:exir/emit/_emit_program.py:285). It is now the maximum version, with value 1 (exir/version.py:9-19). Out-of-tree code that stamped Program.version with it, as the old emitter did, now silently writes v1. Every runtime released before this PR rejects those files, even when they use no new feature. Keep the old name with its old meaning, and give the maximum a new name, which schema/test/test_schema.py keeps in sync with kMaxSupportedSchemaVersion. Minor. Fix this →

Performance

  • extension/pybindings/pybindings.cpp:5749: the host allocation of a shared buffer is a pageable std::vector<uint8_t>. By contrast, allocate_host_buffers pins a method's other host arenas whenever the method has a device buffer (:4337-4339). So in such a method, the per-call _h2d_copy/_d2h_copy of shared host state goes through pageable memory. Allocate it pinned under the same condition. Minor. Fix this →

Specific Comments

  • exir/passes/memory_planning_pass.py:195-196: the message "Cannot share mutable buffers if all other tensors are not on the default mem_id of 1 or in the arena of their device" (extended by this PR) is a double negative. Suggest "Cannot share mutable buffers unless every other tensor is in the default mem_id 1 or in the arena of its device".
  • runtime/executor/method_meta.h:274-277: say explicitly that sharing is by buffer index: buffer i of this method is buffer i of every other method that marks it.
  • exir/version.py:30-31: "stays at version 0, also where they reset its initial data when a method loads late" is hard to parse. Suggest "stays at version 0, even though those runtimes reset its initial data when a method loads late".

Recommendation

Request Changes

The const-prop gap silently produces wrong results on export paths that already enable const-prop together with share_mutable_buffers. It needs a fix and a regression test before merge. The missing cuda.yml entry and the null check are quick fixes that can land with it.

These need discussion before the new runtime rules are frozen:

  • how shared buffers are owned: one core helper or full documentation, and whether load_method should enforce the rules;
  • shipping device sharing without a supported way to produce it;
  • the new meaning of EXECUTORCH_SCHEMA_VERSION.
Review steps
  • Gather context (diff HEAD~8..HEAD: 45 files, +3177/−295)
  • Run three independent reviewers
  • Consolidate findings
  • Fact-check every finding against the code
  • Post review

@shoumikhin
shoumikhin force-pushed the share-device-mutable-buffers branch from c9fe330 to a2e6941 Compare November 22, 2026 06:18
Copilot AI balanced review requested due to automatic review settings November 22, 2026 06:18

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 22, 2026 •

Copy link
Copy Markdown

Claude finished @shoumikhin's task in 43m 1s —— View job


Needs Discussion: the shared-buffer marker, the version gate and Module/pybindings ownership hold together for host state, but device-memory sharing ships with no supported way to export it, and the owner protocol that every runner must follow is implemented twice by hand and only partly specified.

Detailed review of #25425

Summary

This PR does four things:

  • It marks the planned buffers that methods share, in ExecutionPlan.shared_non_const_buffers.
  • It lets those buffers live in device memory.
  • It stamps program version 1 when an older runtime would mishandle such a program.
  • It has Module and the Python Program give every method one allocation of each shared buffer. That allocation is initialized once, through the new Program::initialize_planned_buffer and HierarchicalAllocator::set_initialized_buffers.

Main problems:

  • Device sharing can only be produced by a test helper.
  • The owner protocol is hand-written twice, and the two copies already diverge.
  • The version gate does not reach custom runners.
  • Two documented paths have no tests.

Coverage gaps in this review:

  • Not reviewed: the generated exir/_serialize/generated/executorch_flatbuffer/ExecutionPlan.py.
  • Only partly read:
    • exir/tests/test_memory_planning.py
    • extension/pybindings/test/test_pybindings.py
    • exir/backend/test/test_delegate_scratch.py
    • test/end2end/exported_module.py
    • schema/test/test_schema.py
    • devtools/pte_tool/tests/test_diff_pte.py
    • backends/arm/test/misc/test_diff_pte.py

Backward Compatibility

  • The version gate does not reach runners built against the new runtime (minor).

    • The gate checks the runtime, not the runner. Program::load accepts version 1 as soon as kMaxSupportedSchemaVersion is 1 (runtime/executor/program.cpp:236-244). Whether a v1 program runs correctly depends on the runner, and only Module and pybindings read memory_planned_buffer_is_shared.
    • Custom runners fail silently. A custom runner may share host arenas 1 and 2 across methods. That is what Module with share_memory_arenas did, and what share_mutable_buffers programs needed until now. Such a runner either gives each method its own copy of device-placed state, or lets a method that does not share the buffer overwrite it.
    • The runtime never notices. Those are the two cases that exir/version.py:29-36 bumps the version to prevent. Nothing in Method::init detects a shared buffer that no owner marked initialized, so the failure is invisible.
    • Suggestion: log in Method::init when this happens, and add a release note for custom runners. My confidence in the best hook point is low, because a runner that loads only one method would also trigger the log.

    Fix this →

  • MemoryPlanningPass.run_multimethod now clears self.state (minor).

    • What changed: the new finally: self.reset() (exir/passes/memory_planning_pass.py:610-616) means a subclass that post-processes after super().run_multimethod() sees an empty state. Before this PR the state survived. _SharingPassWithoutMarker (test/models/export_program.py:346-351) already has to read self.state.graph_modules before it calls super.
    • Why it is avoidable: to_executorch now resets every pass before planning (exir/program/_program.py:1926-1929), so the finally only matters for callers that run the pass directly.
    • Suggestion: drop the finally, or document the new contract on run_multimethod.

    Fix this →

API Design

  • Device-memory sharing has no supported producer (major).

    • Only a test helper produces it. The runtime, the schema, the version gate and both owners support a shared buffer in device memory (module.cpp:450-461, pybindings.cpp:5752-5767). In-tree, only the test helper BuffersOnDevicePlanningPass (exir/backend/test/device_util.py:126-164) plans one. It sets spec.device on buffer placeholders before super().run(), and rewires copies with the private _copy_output_spec and _replace_spec.

    • The docs publish that recipe as the user contract. docs/source/backends/cuda/cuda-overview.md:275-294 tells users to:

      • subclass MemoryPlanningPass and set the specs;
      • remove the _h2d_copy that PropagateDevicePass adds;
      • give copies the buffer's own TensorSpec.

      The same paragraph then says the CUDA partitioner does not do this.

    • The result is an interface made of TensorSpec mutation. It is policed only by after-the-fact refusals (_refuse_host_access, _refuse_buffer_copy_specs), and no backend exercises it end to end.

    • Suggestion: either expose this as a real option, or land the device half with its first producer and keep the paragraph out of the CUDA guide until then. A real option could be a MemoryPlanningPass argument that places shared buffers on a device and manages the copies itself, or a backend that produces such programs.

  • The owner protocol is implemented twice by hand and only partly specified (major).

    • The protocol. Every owner must:

      1. scan all methods for a marked index and check that they agree on the device;
      2. size the buffer to the largest method and allocate it;
      3. build a throwaway HierarchicalAllocator of index + 1 spans;
      4. call initialize_planned_buffer for each method that shares the buffer;
      5. mark the buffer initialized in every method's allocator.
    • Who implements it. Module writes it out by hand (module.cpp:412-479, 537-543, 592-595), and so do pybindings (pybindings.cpp:5514-5553, 5745-5831). Out-of-tree runners (JNI, Apple wrappers, custom C++) must write it a third time from program.h:177-197.

    • The two copies already diverge. Module initializes in method_names() order, which is a std::unordered_set and so hash order. Pybindings initialize in program order. _check_shared_initial_data makes the order irrelevant for this exporter's output. A program from another producer would start from different state in the two owners.

    • set_initialized_buffers is a side channel. It is a post-construction setter, and its span must outlive the allocator (hierarchical_allocator.h:127-147). Every owner has to remember to call it, and each keeps an extra bool[] alive just for it (pybindings.cpp:4213, PlannedMemory::initialized_buffers). Making it a constructor argument would make it part of building the allocator.

    • The schema states only part of the contract. schema/program.fbs:428-432 says the shared buffers get "one allocation". It does not say that:

      • the allocation is sized for the largest plan that lists the index;
      • its initial data is loaded once, so plans that store initial data for it must store the same bytes.

      The runtime and the exporter both rely on these two rules.

    • Suggestion: add one runtime-level helper that creates and initializes shared buffer i for all methods, have both owners use it, and state the two rules in the schema. The Fix link below covers the ordering and schema parts.

    Fix this →

Testing

  • Module::load_method(name, planned_memory) is untested on a program that marks shared buffers. module.h:304-308 documents that such a method shares nothing unless the caller supplies the same memory, initialized once. No load_method call under extension/module/test/ passes planned_memory.

    Fix this →

  • The documented refusal of a control flow operator that takes a device-shared buffer is untested (cuda-overview.md:283-285). update_in_cond (exir/tests/test_memory_planning.py:1313-1315) passes x into torch.cond, not the state. test_shared_buffers_check_control_flow_pools covers only branch arenas.

    Fix this →

Performance

  • Pybindings keep a host shared buffer in pageable memory.

    • What happens: it is allocated as a pageable std::vector<uint8_t> (pybindings.cpp:5749). ProgramMemory::allocate_host_buffers pins a method's other host buffers when the method has device buffers, but it skips shared ones (pybindings.cpp:4323-4339).
    • Impact: in a method with device arenas whose shared state stays on the host, copies of that state run at pageable speed. That state is typically the largest host buffer, such as a KV cache.

    Fix this →

Code Quality

  • Sharing policy is spread through to_executorch (minor).

    • Where it lives: about 100 lines of sharing-only logic sit inline in the generic lowering loop of exir/program/_program.py:
      • refusals at 1857-1929;
      • the const-prop exclusion at 1942;
      • unused-buffer removal at 1957-1965;
      • initial-data collection at 2009-2019;
      • the check and metadata copy after run_multimethod at 2047-2052.
    • Repeated predicate: whether a method's pass shares buffers is re-derived at 1961-1964 and 2009-2012, although name in sharing already answers it.

    Fix this →

  • Program::initialize_planned_buffer re-implements part of tensor parsing (minor). program.cpp:563-622 does the following before it calls getTensorDataPtr:

    • re-walks values;
    • re-derives the memory id and the external location;
    • re-validates sizes, dim_order and scalar type;
    • builds a TensorLayout.

    parseTensor already does all of this, so any future change to how initial data is located has to be made twice.

    Fix this →

Specific Comments

  • exir/passes/memory_planning_pass.py:195-197: the message "Cannot share mutable buffers if all other tensors are not on the default mem_id of 1 or in the arena of their device" is a double negative. Suggested wording: "…unless every other tensor is in the default mem_id of 1 or in its device's arena". Keep the phrase default mem_id of 1, which test_memory_planning.py:2357 matches.
  • exir/program/_program.py:2014 walks every node to find buffer placeholders. new_gm.graph.find_nodes(op="placeholder"), as _used_buffers uses at line 271, states the intent.
  • exir/backend/test/device_util.py:174-177: the comment says the _h2d_copy "that stages it for one reads the buffer where it is". That is wrong:
    • _misuse (memory_planning_pass.py:243-245) allows only an _h2d_copy that writes the buffer.
    • An _h2d_copy that reads the buffer is refused.
    • cuda-overview.md:285-286 says the pass has to remove that copy.

Fix this →

Recommendation

Needs Discussion

Maintainers should decide two things before this merges:

  • whether device sharing lands without a supported producer;
  • whether the owner protocol should be one runtime helper rather than code in each runner.

The remaining items are minor and can follow.


  • Gather context (48 files, +3273/−310)
  • Run three independent reviewers over the diff
  • Consolidate findings
  • Fact-check every finding against the code
  • Post review

MemoryPlanningPass(share_mutable_buffers=True) keeps the graphs it planned until
its cross-method step runs, and never forgot them. Using the same pass instance
again, for a second program or after an export that failed, mixed the old graphs
into the new plan. It then failed with errors such as "Cannot share mutable
state if not using default memory ids", or planned memory the program does not
use. Giving one pass to several methods in a dict of passes failed the same way,
because the cross-method step ran once per dict entry instead of once per pass.

to_executorch now starts every sharing pass empty, with the new
MemoryPlanningPass.reset(), so graphs left by an export that failed part way,
for example on its second method, never reach the next plan. The pass also
forgets its graphs when the cross-method step ends, so the second call that a
dict listing it for several methods makes does nothing. to_executorch refuses
two different sharing passes in one program up front, since both would put their
state at the same place in every method. Only passes for methods the program
has, and that use a buffer some sharing method changes, count, so an unused dict
entry or a pass for methods without state changes nothing.

It also refuses programs where a method would read its own copy of shared state
and never see the changes:
- a method planned without sharing that uses such a buffer;
- a method whose delegate keeps such a buffer as its own constant, as a
  partitioner that takes constant data does;
- a method that uses on the host a buffer that a delegate of a sharing method
  changes in its own copy, as happens when a partitioner calls
  tag_mutated_buffer.
Delegates that each keep their own copy are not checked, because whether they
see each other's changes depends on the backend. A method uses a buffer only if
it reads or changes it: non-strict export, the default, keeps every buffer of
the module as an input of every method, and an input that a method never touches
does not count.

This changes behavior for programs exported with share_mutable_buffers: the
refusals above used to export, and the methods silently read stale state. For
example, with the XNNPACK partitioner, a "read" method that computes state * x
while "forward" changes the state is now refused.

With do_quant_fusion_and_const_prop, constant propagation treated a shared
buffer as a constant in a method that only reads it, because that method alone
never changes it. It folded the initial value into the graph, so the method
never saw what the other methods wrote. It now gets the shared buffers and
leaves them alone. Quant fusion no longer reads their values either: a torchao
embedding whose zero point is shared lost it when its first value was 0. A zero
point with no constant value now stays an input of the fused embedding. Every
torchao embedding fusion now casts the zero point with aten._to_copy, which has
an out variant, instead of aten.to, which only constant propagation could
remove; a constant zero point is still folded. Constant propagation that runs
before to_executorch, as some backend pipelines run it, does not get the shared
buffers, and export cannot see a buffer it folded. Such a pipeline has to pass
them to constant_prop_pass as mutable_buffers.

Tested: memory planning tests reuse one pass after an export that failed on its
second method, give one pass to every method in a dict, refuse two sharing
passes and a method without one, and accept a sharing pass listed for a method
the program does not have, a second sharing pass for a helper that never touches
the state, and one for a method whose buffers only a method without sharing
changes. Another test lowers a method that only reads the state to a delegate
that owns it, which is refused with sharing and exports without it. A third
lowers the method that changes the state to a delegate that owns it: a method
that reads the state on the host is refused with sharing and exports without it,
and a helper that never touches the state exports. A method that only reads the
state, exported with constant propagation, keeps it in the shared arena, and so
does a torchao embedding whose zero point another method changes, starting at 0
or at 1. The reuse, refusal, constant propagation and zero point checks fail
without the change.
With share_mutable_buffers, every method that has a mutable buffer of the same
name gets the same memory for it, sized from one of those methods. When two
methods disagree on the buffer's shape or dtype, for example a 2x2 and a 4x4
"state", the size can come from the smaller one, and the methods silently
overwrite each other's memory. When they disagree on its dim order, for example
contiguous in one method and channels last in another, they read each other's
data in the wrong order. When they store different initial data for it, for
example because they were exported from two copies of a model, a runtime has to
pick one, and different runtimes can pick differently.

Refuse such a program at export. The error names the buffer and the shapes,
dtypes and dim orders the methods give it, or the 2 methods whose initial data
differs. Initial data is compared byte for byte, so the same data with NaNs in
it counts as equal, and 0.0 against -0.0 counts as different. This changes
behavior: such a program used to export and then ran with wrong values.

Non-strict export, the default, keeps every buffer as an input of every method,
also of a method that never touches it. Such a method would store initial data
for the buffer too, so a helper exported from a second copy of the model would
be refused, and the program would carry a copy of the data it never uses. A
sharing method now drops the inputs of shared buffers it does not use before
planning.

Tested: new memory planning tests export two methods whose "state" differs in
shape, in dtype, in dim order, and in its stored initial value, and check the
error. They fail without the change. Other cases store the same NaN data in both
methods, which exports, 0.0 against -0.0, which is refused, and different values
where only one method stores its initial data, which exports. A helper that
never touches the state, from a copy of the model with other data, exports and
stores no copy of the state; it is refused without the drop.
With MemoryPlanningPass(share_mutable_buffers=True), every method of a program
plans its mutable state at the same place, memory id 2. Nothing in the program
says so. A runtime can only guess, from a convention and a flag the caller has
to remember, which planned buffer it must give to every method. That guess
breaks as soon as other buffers move around, for example when device memory is
planned too.

Add an optional field, ExecutionPlan.shared_non_const_buffers, that lists the
planned buffers every method marking them shares. The memory planner fills it
when it shares mutable buffers, MethodMeta::memory_planned_buffer_is_shared()
reads it, and diff_pte reports it. The Arm test helper that accepts small
numeric differences between programs now rejects a changed marker. Only a method
that uses a shared buffer marks it, since loading a marked method initializes
the shared state. A helper without state does not mark it, also when export kept
the state as an input it never touches, and gets an empty arena 2: a runtime
that gives every method one arena 2 sizes it for the largest method, so the
state still fits. Programs that share nothing are unchanged, and the field is
added at the end of the table, so older programs still load. to_executorch now
copies each method's metadata again after the cross-method planning step, so
that keys this step adds, such as the new field, reach the program.

Tested: memory planning tests check the marker on a shared state program, and
its absence and an empty arena 2 on a helper without state that export gave an
unused input for the state, a serialization round trip keeps it, MethodMeta
reads it as false where nothing is marked, a Module test reads it from a shared
state program, a diff_pte test reports a changed marker, and an Arm test checks
that a changed marker is not accepted as a small numeric difference.
Loading a method copies the stored initial data of a tensor, for example state
exported with InitializedMutableBufferPass, into the memory planned for it,
every time the method is loaded. That is right while each method owns its
memory. It is wrong for memory several methods share: loading one more method,
or loading one again, puts the initial data back and rewinds state the other
methods have changed.

Give the owner of such memory a way to initialize it once. The new call
Program::initialize_planned_buffer() copies the initial data of every tensor a
method plans in one buffer, from the program or from external data, without
loading the method. Like loading, it returns InvalidProgram for an invalid
scalar type or a tensor value with no data. It returns InvalidArgument for null
planned memory or a buffer the method does not have, and InvalidState for one
already marked initialized. HierarchicalAllocator::set_initialized_buffers()
marks buffers that loading a method must leave as they are. Nothing is marked by
default, so loading works as before for everyone who does not ask for this.

Tested: a new tensor parser test initializes a buffer with the new call, checks
it holds the stored data, and checks that parsing again keeps a value written
into a marked buffer. The existing parser test still sees an unmarked buffer
reset, and the new call refuses a buffer index the method does not have, also
one that would overflow, a buffer already marked, and null planned memory. An
allocator test checks that marking a list of the wrong length aborts. Initial
data in external data and an invalid scalar type are tested with the Python
runtime, which starts calling this function later in this series.
Methods that share state, such as prefill and decode sharing a KV cache, must
read and write the same memory for it. The C++ Module shared memory between
methods only with share_memory_arenas, and only in host memory: it refused a
program with device buffers when the flag was set.

Now Module reads the marker the program records. Every method that marks a
buffer gets one allocation of it, in host or device memory, with no flag needed.
That allocation is made when the first such method loads, gets the initial data
the program stores for it from every method that marks it, in program order, and
lives as long as the Module. Loading, unloading or reloading a method does not
reset it, and a new Module starts from the initial data. A method
given its own planned_memory in load_method() still uses only that.

This changes behaviour for newly exported programs that share mutable buffers:
the default Module now shares their state between methods, as
share_memory_arenas did on the host, and an output that aliases that state can
change when another method runs. The Python _load_for_executorch builds a C++
Module, so it shares their state too. share_memory_arenas keeps working for
older programs. A program that marks its shared buffers and has device memory
now loads instead of being refused; the exporter does not plan shared buffers in
device memory yet, so only a program built by hand reaches this path for now.
With a program that marks nothing it still refuses device memory (NotSupported),
because it cannot tell which device buffers hold state. Unmarked device buffers
are never shared.

Tested: a Module test checks that a program that marks its state shares it
between methods, with and without share_memory_arenas: a reader first loaded
after the writer changed the state, a reload of the reader, and a read after
every method was unloaded all see the changed state. Another checks that 2
shared buffers, each changed by one method that alone stores its initial value,
are both seen by a third method that stores neither. A third checks that
initialize_planned_buffer() writes only the buffer it is asked for. Older tests
check that share_memory_arenas still shares the state of a program that does not
mark it, now checking that it marks nothing, and still refuses device memory in
such a program. The first 2 fail without the change, the first also when the
state is initialized on each method's first load or dropped once every method
is unloaded, and the third without the buffer filter of the commit before.
…uffer

The Python runtime shared its host arenas between host-only methods, and gave
every method with a device buffer its own arenas, so such a method had its own
copy of the state. A method that used the same arena number without sharing it
could also overwrite the shared state, because every host-only method got the
same program-wide host arenas.

Now the Python runtime reads the marker the program records, as the C++ Module
does. Every method that marks a buffer gets one allocation of it, in host or
device memory. That allocation is made when the first such method loads, gets
the initial data the program stores for it from every method that marks it, in
the .pte or in external data, and lives as long as the Python program. It is
separate from the program-wide host arenas, so a method that does not mark the
buffer cannot overwrite it. Loading a method does not reset it.

This changes behaviour for newly exported programs that share mutable buffers:
with the program API, methods with device memory now share the state too,
loading a method no longer resets it, and an output that aliases it can change
when another method runs. If methods place a shared buffer on different devices,
no method that marks it loads, as with Module; the other methods still load.

Tested: Python tests check that methods loaded late, or loaded again through the
program API, keep the state, also when its initial value is in external data;
that 2 shared buffers, each changed by one method that alone stores its initial
value, are both seen by a third method that stores neither, also when it loads
first; that a method using arena 2 without marking it leaves the shared state
alone when every method is loaded first; that a shared buffer whose other method
has an invalid scalar type fails to load with an error; and that a shared
buffer that methods place on different devices does not load, with the program
API or with _load_for_executorch. All of them fail without the change, except
the _load_for_executorch case, which checks the Module from the commit before.
A last test checks that a shared buffer that the first method of a program
plans smaller, as a hand-edited program does, gets the larger size with both
APIs. The runtime before sized it so too, so this test fails only when Module or
the Python program sizes it from the first method.
A runtime that ignores ExecutionPlan.shared_non_const_buffers gives every
host-only method one buffer for each planned memory index, or with
share_memory_arenas one buffer for all methods. For most programs with shared
host state that is the old behavior, and it is still right. But a method that
does not mark a shared buffer can keep data of its own in the bytes of the
shared state, for example when a custom planning pass puts its tensors or its
delegates' scratch memory at memory id 2. Such a runtime then lets that method
overwrite the state, without any error.

Each program now gets the lowest version that it needs. A program where a
host-only method that does not mark a buffer has data, a tensor or delegate
scratch, in the shared bytes of that buffer gets version 1, which the runtime
now accepts. Data after the shared bytes, tensors with no elements, or shared
state of no bytes, is safe. A method with device memory gets buffers of its own
from such runtimes, so it does not count. Every other program stays at version
0, EXECUTORCH_SCHEMA_VERSION as before, so older runtimes keep loading it.
MAX_EXECUTORCH_SCHEMA_VERSION is the highest version the exporter stamps, and
SHARED_NON_CONST_BUFFERS_VERSION the version of this feature.

Runtimes 1.5.0 to 1.6 refuse a version 1 file. Older runtimes do not check the
version, so they load it and run it wrongly. They all ran the layout above
correctly only without share_memory_arenas, where nothing is shared, not even
the state. Other shared host state stays at version 0, although those runtimes
run it with 2 differences: a method that loads late resets the state to its
initial data, and a method that stores no initial data reads zeros if no
method that stores it has loaded yet. They do that today, and
version 1 would make them refuse host programs that they run now.

Program and Method do not read the marker. A runner that plans its own memory
has to give every method that marks a buffer one allocation of it to run a
version 1 file correctly, as Module and the Python runtime do. The documentation
of the version says so.

Tested: memory planning tests stamp version 1 when the helper's data starts at
or inside the bytes of the state, and version 0 when it starts after them, when
its results have no elements, for a helper with device memory, and for shared
host state without such a helper. A delegate scratch test stamps version 1 when
a helper's scratch is planned at memory id 2 and version 0 when it is planned at
memory id 1. A schema test checks that MAX_EXECUTORCH_SCHEMA_VERSION is the
highest version in exir/version.py and is at most the runtime's version.
MemoryPlanningPass(share_mutable_buffers=True) always planned shared state in
host memory, even when the state was placed on a device. So a backend that keeps
a KV cache on the GPU could not share it between methods.

Now, with enable_non_cpu_memory_planning on, the default, the shared arena goes
on the device the state is placed on, at memory id 2 in every method that uses a
shared buffer, whose device arenas move up by one. Only one device, counting the
host, can hold shared buffers. A method that never touches a shared buffer
already drops its input, so it gets no device memory for it either.

Planning a buffer in device memory adds no copies, so export refuses any use of
a shared device buffer except a delegate whose target_device is that device,
et_copy._d2h_copy reading it, et_copy._h2d_copy writing it, an op that reads
only its sizes, strides, storage offset or element count, and the write-back of
its new value.
Export follows the buffer through views and through the delegate result that
holds it; the delegate's other results are plain tensors. A method cannot return
it, and a control flow operator cannot take it. Export also refuses one buffer
on two devices, a mutable buffer that another step already planned, and a device
tensor left in host arena 1. A buffer that skip_h2d_for_constants keeps on the
device now works with share_mutable_buffers if no method changes it.

To put the state on a device, a MemoryPlanningPass subclass sets spec.device on
its placeholders and removes the per-call et_copy._h2d_copy where a delegate
reads it. No partitioner here does that yet. A runtime that ignores the marker
would give a method with device memory its own copy of the state, so such a
program gets version 1.

Two checks also apply to shared host state. The memory id check now looks inside
control flow branches, so a branch tensor planned on top of the state is
refused. And a copy into a shared buffer with a
TensorSpec of its own, as a custom pass can make, is refused, since the copy
would write memory apart from the buffer and views made earlier would point
elsewhere. Before, such a host program ran with wrong values.

Tested: planning tests cover each layout and refusal above, other than the
control flow operator, which is refused like any host op, and the version. They
accept delegates that read the buffer directly, through a view or in place, a
delegate that also returns a second result kept on the device, size and element
count reads, and copies that name their source by keyword. A method that never
touches the buffer gets no device memory for it. A Module test runs 3 methods on
one test device allocation, of the state's size, across reloads, with and
without share_memory_arenas. Python tests check that without a device allocator
only the stateful method fails, and that on a CUDA GPU the methods share the
state, a test the CUDA workflow now runs.
@shoumikhin
shoumikhin force-pushed the share-device-mutable-buffers branch from a2e6941 to 7899155 Compare November 23, 2026 19:28
Copilot AI balanced review requested due to automatic review settings November 23, 2026 19:29
@shoumikhin

Copy link
Copy Markdown
Contributor Author

@claude review effort=max

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 23, 2026 •

Copy link
Copy Markdown

Claude finished @shoumikhin's task in 49m 46s —— View job


Needs Discussion: the core runtime now accepts version 1 programs even though loading a method never acts on the shared-buffer marker, device-memory sharing has no supported producer, and the owner protocol is implemented separately in Module and in pybindings, whose copies already differ.

Detailed review

PR Review: #25425

Summary

This PR marks the arena that holds the mutable state methods share (ExecutionPlan.shared_non_const_buffers) and lets that arena live in device memory. Module and the Python runtime each give every marking method one allocation, initialized once. Programs that older runtimes would run wrongly are stamped as schema version 1.

The main problems are in the design:

  • Program accepts version 1, but whether a program runs correctly is left entirely to the runner.
  • The device half can only be reached by user graph surgery.
  • The owner protocol has no runtime API.

Not covered: the generated exir/_serialize/generated/executorch_flatbuffer/ExecutionPlan.py was not reviewed. The devtools/pte_tool, Arm test and BUCK/targets.bzl changes were only skimmed.

Backward Compatibility

  • Program accepts version 1, but loading a method never acts on the marker the bump protects (major).

    • kMaxSupportedSchemaVersion = 1 (runtime/executor/program.h:90) makes Program::load accept version 1 files.
    • Program::load_method and Method::init never read shared_non_const_buffers. Only MethodMeta::memory_planned_buffer_is_shared exposes it, and only Module and pybindings act on it.
    • Trigger: a multi-method runner built on Program::load_method that shares memory the way share_memory_arenas and the Python runtime did before this PR. Host-only methods get one buffer per index, and a method with device memory gets buffers of its own (exir/emit/_emit_program.py:89-90). Once the runner moves to this runtime, it loads version 1 files without an error.
    • Result: it runs the file the way exir/version.py:30-34 describes for runtimes that ignore the marker:
      • an unmarked method can overwrite the shared bytes;
      • a device-planned method gets its own copy of the state.
    • No out-of-tree change is needed to produce such a file. _program_version (exir/emit/_emit_program.py:91-96) returns version 1 when a method with a non-CPU non_const_buffer_device entry marks any buffer, for example a device-planned method that uses host shared state. enable_non_cpu_memory_planning defaults to True.
    • The only guidance for runner authors is header prose (program.h:85-88, :155-157).
    • Suggestion: at minimum, Method::init should log when a marked buffer is not flagged in initialized_buffers(). Failing instead of logging needs discussion, because a runner that loads only one method is correct today.
    • Out-of-tree runner authors also need a release note.

    Fix this →

  • EXECUTORCH_SCHEMA_VERSION changed meaning but kept its name (minor).

    • Before: "stamped into Program.version of every exported PTE file", kept in sync with kMaxSupportedSchemaVersion.
    • Now (exir/version.py:9-11): the floor. The new MAX_EXECUTORCH_SCHEMA_VERSION is the one kept in sync.
    • Out-of-tree code that compares program.version, or the runtime maximum, against it now gets a different answer, and nothing reports an error.
    • Suggestion: keep the old name for the maximum and give the floor a new name.

    Fix this →

API Design

  • Device-memory sharing has no supported producer (major).

    • The shared arena goes to a device only if every placeholder of the buffer, in every method, already carries spec.device/spec.device_index (exir/passes/memory_planning_pass.py:639-664).
    • The docs (docs/source/backends/cuda/cuda-overview.md:277-300) tell users to write a MemoryPlanningPass subclass that sets those fields, removes the et_copy._h2d_copy nodes that PropagateDevicePass inserted, and gives each copy the buffer's own TensorSpec. That is graph surgery on private internals.
    • The only implementations are test helpers (exir/backend/test/device_util.py, exir/tests/test_memory_planning.py).
    • The docs say the CUDA partitioner does not do this, and the in-tree CUDA exports keep share_mutable_buffers off (examples/models/muse-glimmer/export/export_dflash.py:43-46, examples/models/voxtral_tts/export_voxtral_tts.py:529).
    • MemoryPlanningPass.__init__ documents none of it.
    • This path is the reason for _misuse/_host_use/_refuse_host_access, the device rules in _program_version, and the device branches in Module and pybindings. As landed, only test helpers show how to meet its contract.
    • Suggestion: either add a first-class option that does the placement and removes the copies, or land the device half together with its first real producer.
  • The owner protocol is implemented in two places, and the copies already differ (major).

    • Module::get_shared_buffer (extension/module/module.cpp:412-480) and pybindings (extension/pybindings/pybindings.cpp:5514-5543, 5745-5831) each re-derive the same rules:
      • size the buffer to the largest size among the methods that mark it;
      • require those methods to agree on its device;
      • allocate it once;
      • call initialize_planned_buffer for every marking method in program order, through a throwaway index + 1 HierarchicalAllocator padded with CPU devices;
      • mark the buffer as initialized on every load.
    • They already differ:
      • Module's init failure (module.cpp:474-475) carries no message, so the log names neither the method nor the buffer. Pybindings names both (pybindings.cpp:5781).
      • The device-mismatch messages differ ("shared buffer %zu" vs "shared planned buffer %zu").
    • Any other runner, which is the case in the first Backward Compatibility finding, has to rebuild all this from the prose in program.h:155-157,182-207 and module.h:295-308.
    • Suggestion: add one runtime helper that both runners use. Also state the largest-size and initialize-once rules in schema/program.fbs:428-432, because they are part of the version 1 format contract.

    Fix this →

  • set_initialized_buffers is set after construction, unlike the devices (minor) (runtime/core/hierarchical_allocator.h:127-156).

    • planned_buffer_devices is a constructor argument. The initialized flags change what Method::init writes, yet they are set afterwards, through the class's only setter.
    • The span is borrowed and must outlive the allocator, and a size mismatch aborts.
    • Suggestion: a constructor overload, matching how the devices are passed.
    • The name says what the owner did, not that the runtime will skip copying initial data into those buffers.

    Fix this →

  • Constant propagation still folds shared state by default (minor, needs discussion) (exir/passes/constant_prop_pass.py:516, 527-531).

    • mutable_buffers is opt-in. to_executorch passes it (exir/program/_program.py:1942).
    • Backend passes that run constant_prop_pass on the whole program before to_executorch do not pass it, for example backends/transforms/fused_quant/optimization_passes/constant_fold.py:23 and backends/cadence/aot/weight_packing.py:335.
    • Trigger: one method only reads a buffer that another method changes. These passes fold that buffer into a constant, and, as the new docstring says, export can then no longer see it.
    • Result: that method reads the initial value forever, and nothing reports it.
    • Suggestion: discuss a safer default, or a way for those pipelines to learn which buffers the program shares.
    • Naming: mutable_buffers is also easy to confuse with buffers_to_mutate, which means something else.
  • There is no way to reset shared state short of a new Module or program (question).

    • Before this change, with share_memory_arenas, reloading a method re-applied the stored initial data. exir/version.py:35-37 still describes that for older runtimes.
    • The marked allocation now lives as long as the Module or Program (module.h:298-301, runtime/__init__.py:274-276), and a new Module also re-initializes every delegate.
    • Is a reset_shared_buffers() built on initialize_planned_buffer planned, or is dropping that workflow intended?

Testing

  • The torch.cond refusal is documented but untested.

    • cuda-overview.md:287-289 says a control-flow operator such as torch.cond cannot take a shared buffer that is in device memory, "even when every branch copies it first".
    • No test passes the buffer into cond. update_in_cond (exir/tests/test_memory_planning.py:1313-1315) passes (x,), so its uses at :2355-2361 test the mem_id check instead.

    Fix this →

  • The Module-path check in test_shared_buffer_on_two_devices_is_refused is too loose (extension/pybindings/test/test_pybindings.py:4534-4535).

    • It only matches "Failed to execute method forward", which any load or run failure produces.
    • Suggestion: pin the error code, as the test at :263-270 does.

    Fix this →

Performance

  • The shared host buffer is pageable (extension/pybindings/pybindings.cpp:5748-5751).

    • ProgramMemory::allocate_host_buffers (:4323-4349) pins planned host buffers whenever the method has device buffers.
    • A device-planned method whose shared state stays on the host copies that state between host and device, yet its shared buffer is pageable. This is the version 1 case above.

    Fix this →

  • A program-level fact is recomputed on every load_method (extension/module/module.cpp:493-508).

    • With share_memory_arenas, each load rebuilds method_names() and walks every method's metadata to compute marks_shared_buffers.
    • Whether the program marks any buffer cannot change between loads, so this only needs computing once.

    Fix this →

Code Quality

  • Program::initialize_planned_buffer re-implements part of tensor parsing, and the two already disagree (runtime/executor/program.cpp:566-611).

    • It skips a null values entry with continue, where Method::parse_values returns InvalidProgram (method.cpp:389-395).
    • It reuses the "Null value at index" message for a Tensor value with a null payload.
    • It derives the tensor layout itself instead of sharing parseTensor's code.
    • Result: owner initialization and load_method accept different sets of malformed programs.

    Fix this →

  • to_executorch grows by about 75 inline lines of sharing checks (exir/program/_program.py:1857-1929).

    • It then re-derives the sharing condition at :1961-1964 and :2009-2012, where name in sharing gives the same result.

    Fix this →

  • _remove_unused_buffers duplicates an existing pass and leaves stale data (exir/program/_program.py:278-293).

    • It duplicates exir/passes/remove_unused_parameters_pass.py.
    • Unlike that pass, it leaves the removed entry in state_dict/constants, so the program keeps data for an input it no longer has.

    Fix this →

Specific Comments

  • exir/passes/memory_planning_pass.py:195-196: "if all other tensors are not on the default mem_id of 1 or in the arena of their device" is a double negative. State the requirement directly, e.g. "every other tensor must be in mem_id 1 or in its device's arena".
  • exir/passes/memory_planning_pass.py:323-327 and cuda-overview.md:287: these list "the write-back of its new value" as an allowed use.
    • The aten.copy_ write-back that insert_write_back_for_buffers_pass inserts is refused ("uses it on the host").
    • So the error names the rejected write-back node right next to text that seems to allow it.
    • Say "returning it as a buffer mutation output" instead.
  • exir/version.py:26-43: 18 lines of prose in a constants file. They include a release matrix ("before 1.5.0 … 1.5.0 to 1.6 refuse them") that will go stale. Keep what each constant means and move the rest to the docs or the release notes.
  • docs/source/backends/cuda/cuda-overview.md:298-300: "Such a program gets version 1" comes right after "delegates that each keep their own copy", so it reads as if that program gets version 1. Version 1 comes from a device-planned method that marks a buffer.
  • exir/schema.py:308-309: "the buffers every execution plan that lists the same index shares" is hard to parse. Mirror the wording in schema/program.fbs:428-431.
  • extension/module/module.h:82-84: "sized to the max across all methods" no longer holds. get_max_mem_planned_buffer_sizes (module.cpp:634-641) now leaves out device and marked buffers.
  • extension/module/module.cpp:515-517: "Export it with share_mutable_buffers=True" does not help a device program without state. _share_mutable_buffers marks only methods that use shared state, so that program still marks nothing and still fails. Lead with disabling share_memory_arenas.
  • extension/pybindings/pybindings.cpp:4318-4321: is_shared_buffer is also true for the program-wide arenas that a host-only method borrows (:5818-5825), and those are not marked shared. is_borrowed_buffer would match what it tests.
  • extension/pybindings/test/test_pybindings.py:4500: test_invalid_method_does_not_abort_loading_shared_state reads as if loading goes ahead, but the test asserts that loading forward fails. If the point is that a corrupt sharing method raises instead of aborting the process, say that in the name, e.g. test_invalid_sharing_method_raises_instead_of_aborting.
  • exir/program/_program.py:2014: this walks every node to look up node.target in inputs_to_buffers. _used_buffers (:271) does the same lookup with graph.find_nodes(op="placeholder").

Recommendation

Needs Discussion

The two major design questions are for maintainers:

  1. Should Program accept version 1 while correctness depends on the runner?
  2. Should the device half land before anything outside the tests can produce it?

The duplicated owner protocol should become a runtime API before more runners copy it. Everything else is minor.

This branch has not been deployed

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

Labels

ciflow/trunk CLA Signed This label is managed by the Facebook bot. Authors need to sign the CLA before a PR can be reviewed. module: arm Issues related to arm backend release notes: exir Changes to any dialects and passes on these dialects, such as memory planning

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants