Repository navigation
Share mutable buffers between methods in device memory - #25425
shoumikhin wants to merge 8 commits into
Conversation
🔗 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 FailureAs of commit 7899155 with merge base d811540 ( 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. |
|
@claude review effort=max |
|
Claude finished @shoumikhin's task in 53m 15s —— View job PR Review: #25425Request Changes. With Detailed reviewSummaryMutable buffers that several methods share can now live in device memory:
Verdict: the review found:
Not fully reviewed:
Code Quality
Infrastructure
Testing
API Design
Backward Compatibility
Performance
Specific Comments
RecommendationRequest Changes The const-prop gap silently produces wrong results on export paths that already enable const-prop together with These need discussion before the new runtime rules are frozen:
Review steps
|
c9fe330 to
a2e6941
Compare
|
@claude review effort=max |
|
Claude finished @shoumikhin's task in 43m 1s —— View job Needs Discussion: the shared-buffer marker, the version gate and Detailed review of #25425SummaryThis PR does four things:
Main problems:
Coverage gaps in this review:
Backward Compatibility
API Design
Testing
Performance
Code Quality
Specific Comments
RecommendationNeeds Discussion Maintainers should decide two things before this merges:
The remaining items are minor and can follow.
|
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.
a2e6941 to
7899155
Compare
|
@claude review effort=max |
|
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 reviewPR Review: #25425SummaryThis PR marks the arena that holds the mutable state methods share ( The main problems are in the design:
Not covered: the generated Backward Compatibility
API Design
Testing
Performance
Code Quality
Specific Comments
RecommendationNeeds Discussion The two major design questions are for maintainers:
The duplicated owner protocol should become a runtime API before more runners copy it. Everything else is minor. |
Summary
Methods can share state, like a KV cache.
MemoryPlanningPass(share_mutable_buffers=True)plansit once, but only in host memory, and runtimes give a method with device memory its own copy.
This change fixes that:
ExecutionPlan.shared_non_const_buffers.Program::initialize_planned_buffer()initializes a planned buffer once.Moduleand the Python runtime give every method that marks a buffer one allocation of it, inhost or device memory. A runner that plans its own memory must do the same.
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.
export allows only a delegate on that device,
et_copycopies, metadata reads and thewrite-back to use it.
Behavior changes, for programs exported with
share_mutable_buffers:Module,_load_for_executorchand 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.
do_quant_fusion_and_const_prop, shared state, such as an embedding's zero point, is nolonger folded into a constant. Constant propagation run before
to_executorchneeds the newmutable_buffersargument.share_memory_arenasloads marked device programs, andskip_h2d_for_constantsworks for abuffer that no method changes.
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
TensorSpecof its own.Test plan
Built from source on Linux x86_64. New tests cover export, serialization,
Moduleand the Pythonruntime; 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.