Repository navigation
Description
Request description
Overview
In multi-device settings that include a heterogenous device setup including e.g. the CPU and some kind of accelerator, memory is often shared between the CPU and the accelerator. While the memory may be shared, explicit flush of written memory regions may be required in case non-coherent shared memory.
Currently there exist multiple gaps in the compiler to allow a true zero-copy lowering path for this use case.
This ticket proposes steps to close these gaps and aims to describe an implementation that achieves a true zero-copy lowering path:
The zero-copy path must preserve a synchronization operation representing the handoff between devices, even when no data copy is required. Allocation planning must make the transfer result alias the source storage. Transfer canonicalization and elision must preserve required cache maintenance and producer/consumer dependencies.
The current lowering for flow.tensor.transfer
Currently handling device assignment happens through the insertion of flow transfer operations on tensors:
%1 = flow.tensor.transfer %0 : tensor<16x16xi8> to #hal.device.affinity<@device_b>these sub-sequently lower to async transfer in the stream dialect:
stream.async.transfer %src : ... -> to(#hal.device.affinity<@device_b>) ...In the lowering from stream async to stream cmd this then lowers outgoing transfers to (
iree/compiler/src/iree/compiler/Dialect/Stream/Transforms/ScheduleAllocation.cpp
Line 677 in 9acea6a
| applyAsyncTransferOp(IREE::Stream::AffinityAttr executionAffinityAttr, |
stream.cmd.copy %src[...], %dst[...], %length : ...
stream.cmd.flush to(#hal.device.affinity<@device_b>) %dst[...] : ...incoming transfers on the other hand lower to: stream.cmd.invalidate and stream.cmd.copy
Missing lowering for stream.cmd.flush and stream.cmd.invalidate
The first gap in the lowering is that lowering of stream.cmd.flush is simply not implemented. The operations is simply erased in the current lowering. See
| struct CmdFlushOpPattern : StreamConversionPattern<IREE::Stream::CmdFlushOp> { |
Not only is the lowering of the operation missing also its implementation in the HAL command buffer is not present. The lowering to be implemented should follow what is implemented for the IREE::Stream::CmdCopyOp
| struct CmdCopyOpPattern : StreamConversionPattern<IREE::Stream::CmdCopyOp> { |
IREE::HAL::CommandBufferCopyBufferOp which is sub-sequently lowered to the VM call here iree/compiler/src/iree/compiler/Dialect/HAL/Conversion/HALToVM/ConvertCommandBufferOps.cpp
Line 206 in 9acea6a
| class CommandBufferCopyBufferOpConversion |
It also requires the extension of the HAL with the correct command buffer handler. See handling for hal.command_buffer.copy_buffer it should be analogous.
Similar for stream.cmd.invalidate
Note that the HAL implementation already provides functions for buffer flush and invalidation:
iree_hal_buffer_mapping_flush_rangeiree_hal_buffer_mapping_invalidate_range
Copy operation when lowering
The current lowering can produce a copy of the buffer which breaks a true zero-copy path:
stream.cmd.copy %src[...], %dst[...], %length : ...
stream.cmd.flush to(#hal.device.affinity<@device_b>) %dst[...] : ...Transfers can be eliminated when resource lifetimes match and the affinity/topology checks permit it. This replaces the transfer result with its source.
| IREE::Stream::AsyncTransferOp transferOp, ElisionAnalysis &analysis, |
For true zero-copy we need to avoid the introduction of stream.cmd.copy.
To achieve this we should allow to communicate that no explicit buffer allocation and copy is required for flow.tensor.transfer and stream.async.transfer. Either derived from the device affinity or from an explicit attribute set on the operation. Zero-copy requires that the backing allocation is accessible to both devices and satisfies their usage requirements. Device affinity or an operation attribute must convey or establish this compatibility, shared physical memory alone is insufficient.
This should control the lowering of stream.async.transfer to avoid the insertion of the stream.cmd.copy
Note that simply leaving out the copy is not possible, there also has to be change in allocation so that the consumers read from the correct buffer. This needs to be handled in
iree/compiler/src/iree/compiler/Dialect/Stream/Transforms/ScheduleAllocation.cpp
Line 1642 in 9acea6a
| allocateExecutionRegion(IREE::Stream::AsyncExecuteOp executeOp, |
Flush and invalidate operations must have execution-time ordering semantics. A flush must execute after the writes it makes available, and completion must be included in the handoff’s signaled timepoint/fence. An invalidate must execute after the corresponding producer completion and before dependent reads. Implementations must not perform cache maintenance merely during command-buffer recording. Backends may satisfy these requirements through queued commands, ordered host work, or equivalent synchronization guarantees.
Invalidate/flush is ignored for single copy/fill
The current matching for transfer operations is ignoring flush/invalidate
iree/compiler/src/iree/compiler/Dialect/HAL/Conversion/StreamToHAL/Patterns.cpp
Line 1232 in 9acea6a
| // } |
This optimization must preserve required flush/invalidate operations or decline the optimization. A region containing only cache maintenance after copy removal must retain its execution and synchronization semantics.
Cases to be handled
- Coherent shared memory: shared backing allocation, no copy, preserved ordering.
- Non-coherent shared memory: shared backing allocation, no copy, correctly ordered flush/invalidate as required in each direction.
- Incompatible or discrete memory: retain allocation and copy.
- Multiple consumers and in-place updates: preserve tensor semantics and allocation lifetime.
What component(s) does this issue relate to?
No response
Additional context
No response
Activity
[-]Multi-device Zero-Copy Path: Missing lowering for stream.cmd.flush and zero-copy path[/-][+]Multi-device Zero-Copy Path: Missing lowering for stream.cmd.flush/invalidate and zero-copy path[/+]purnima-nlp commentedon Sep 16, 2026
hey i have working on this already , may you assign it to me
Manewing commentedon Sep 21, 2026
Hey @purnima-nlp
thanks for looking into this and also for reaching out on this! I opened this issue after I saw a discussion on Discord regarding this topic, now there already has been some work done by @l0r3m1psum as well [0]. So we will have to take a look how to align the work and avoid duplication.
Generally though very nice to see movement on this topic :) let's see how we can push this together!
[0] main...l0r3m1psum:iree:hal-command-buffer-flush
purnima-nlp commentedon Sep 21, 2026
Yes I would love to contribute on this issue, let me see what's already implemented.
I will comment soon on this
devtbi commentedon Sep 22, 2026
for context, two items should be mentioned here, 1) where the current topology was introduced: #20885 / #20856 2) runtime toplogy that was added here: #23573. We should look into having the device capabilities & toplogy /parts of it mirrored to compile-time, if that makes sense. Looks a bit inconsistent right now.
on flush: I think stream flush docs "Transfers a resource to an external target. The resource memory is made available to the target and can be made visible there using
stream.cmd.invalidate." is a bit misleading. All flush_range implementations currently do is a 'host-CPU (mapped-memory) flush, such that host writes become available to the device owning the buffer', e.g. (vkFlushMappedMemoryRanges) - might be the reason why it's not lowered currently? just guessing.Generally I agree with adding some attribute to transfer to establish the kind of transfer, instead of attempting to clean up after-the-fact. This can optionally be derived from the topology. Maybe starting with copy | alias (which will be "NATIVE" or "IMPORT" in terms of the runtime topology terminology, I don't think we need to differentiate import at compile-time). Not sure if coherence should be an attribute of transfer, and then resolved by resolve_memory_properties, or inferred from topology and the buffers.
purnima-nlp commentedon Sep 22, 2026
Thanks for your comment this is helpful for me. I have few things to ask you below !! please provide your valuable opinion
For my PR, I was intentionally keeping the scope limited to introducing HAL/runtime command-buffer plumbing for flush/invalidate and leaving Stream-to-HAL lowering disabled. The current inline implementation uses
iree_hal_buffer_mapping_flush_range/invalidate_range, so as you pointed out that is specifically mapped host-memory cache maintenance rather than a generic device-to-device ownership transfer.My current thinking was to keep these HAL operations as the runtime representation for that cache-maintenance step, and handle the actual zero-copy transfer decision separately. In particular, I agree that distinguishing something like
copyvsaliasearlier on the transfer seems cleaner than trying to infer it after allocation/scheduling.Would you prefer that
hal.command_buffer.flush_buffer/invalidate_bufferbe explicitly scoped/documented as mapped-memory cache maintenance only, withstream.cmd.flush/invalidateremaining a higher-level concept for now? Or do you think these HAL operations should not exist independently and the design should instead start from transfer kind/topology first?Also, for the transfer kind, would you expect
copy | aliasto be carried onflow.tensor.transfer/stream.async.transfer, with topology used to derive it where possible, while coherence is resolved separately from buffer/memory properties?l0r3m1psum commentedon Sep 27, 2026
Hello everyone, sorry for my late reply to this thread but I had a super busy week at work. As stated by @Manewing I started working on this PR with his kind guidance on Discord. PR #24962 is the work I was doing. If I can do something as well to help close this issue I am happy to help!
purnima-nlp commentedon Oct 7, 2026
@Manewing @l0r3m1psum since the HAL/runtime flush/invalidate part is already in progress in #24945/#24962, I’d like to continue contributing to the remaining pieces of this issue.
Could you please point me to which parts are still unclaimed and would be useful to take as a separate PR?
From the issue, I see possible follow-up areas such as:
copyvsalias) earlier in Flow/Stream,stream.cmd.copyfor valid zero-copy transfers while preserving synchronization/cache maintenance,I’m happy to pick one of these and keep the scope small to avoid overlapping with ongoing work.
[HAL] Add command buffer flush and invalidate operations (#24945)
Manewing commentedon Oct 20, 2026
Hey,
sry for taking so long to come back to this ticket. I missed the comments.
I think what would make sense next would be to actually introduce a distinction is stream whether A) a transfer requires an allocation and copying or B) if reuse (with flushing) of an existing buffer is sufficient:
A) allocate a destination buffer and copy the data, then flush if required
B) Re-use the existing buffer, flush if required
This means we will probably need to change ElideAsyncCopies.cpp next, we need to avoid that removing a data copy removes the required cache maintenance.
1. Storage choice
This could mean a storage attribute on
stream.async.transfer:This is independent of cache maintenance it just handles allocation. This needs some updated in StreamOps.cpp to allow using the new attribute during construction etc. It also needs some care in StreamOpsFolder.cpp
2. Prevent elision
Currently, topology information such as unified memory or transparent access can lead to:
We need to keep the transfer in case of reuse:
3. Adjust lowering in async-to-cmd
applyAsyncTransferOpmust omitstream.cmd.copyfor reuse transfers, while emitting the required flush/invalidate operations on the shared range.4. Proper lowering for stream.cmd.flush and stream.cmd.invalidate
We need to preserve the required operations and lower them to their respective HAL command buffer ops
Implementation
I think we can do this step wise, broken up as the steps I described above.
Though I think it should be possible to start with both 1 and 4. I think 2, 3 need to be done in order after 1 has been implemented.
Let me know what you think!
purnima-nlp commentedon Oct 21, 2026
Thanks for getting back to this and for breaking it down so clearly.
My understanding is that step 1 gives us the storage semantics we need for the later zero-copy changes, while step 4 is largely independent and can connect the existing Stream flush/invalidate ops to the HAL command-buffer ops.
I wish to start with step 1 and step 4 in parallel, keeping both PRs separate. For step 1, I’ll focus first on introducing and preserving the storage choice on
stream.async.transfer, without changing allocation/elision behavior yet.That should give us a clean base for steps 2 and 3 afterwards. I'm open to suggestions
Thanks for your guidance and reviews again.
Manewing commentedon Oct 21, 2026
@purnima-nlp sounds good, looking forward to the changes! :)
[Stream] Add storage policy to async transfers (#25143)
Manewing commentedon Nov 12, 2026
The original plan still looks right. The next step is to make an explicitly selected
storage=reusetransfer work through the compiler. We can tackle automatically choosing reuse afterward.Several pieces are already in place:
Now we need to connect these pieces so that removing a copy also removes the extra allocation, while keeping the synchronization and cache maintenance that the consumer needs.
For example, a copied transfer might look like this:
With compatible shared storage and
storage=reuse, we want:The allocation choice matters: we cannot simply remove the copy if the CPU's original buffer is inaccessible to the accelerator. For buffers created by the compiler, allocation planning must satisfy both devices' requirements. For externally supplied buffers, we need to establish that the supplied allocation is suitable.
Implementing
storage=reusetherefore means updating the existing compiler machinery to:That last point is easy to miss. Consider this illustrative tensor-level example:
consume(original)must still see the original value. Reusing storage for the transfer does not automatically make it safe to overwrite that storage later. The compiler may need a protective copy forupdate, even though the transfer itself does not copy anything.We should also keep optimizations that prove a transfer unnecessary. For example, transferring a value from A to B and straight back to A, with no intervening work on B, can still fold away when the existing type and affinity checks permit it. The storage policy describes how a transfer that remains is implemented; it does not force every transfer to remain in the program.
The ordering requirement is equally important. For the non-coherent CPU-to-accelerator example, we need:
Flushing while recording a command buffer would be too early if the CPU writes happen later. Likewise, reporting successful completion before the required maintenance finishes would allow the consumer to read too early. Flush/invalidate provide cache maintenance; barriers and timepoints provide the ordering. Failures must reach the dependent work rather than letting it proceed as though the transfer succeeded.
For coherent shared memory, the cache operation may be unnecessary, but the consumer must still wait for the producer. In the reverse direction, device writes must finish before any required invalidation and subsequent CPU reads. The appropriate maintenance depends on the actual buffer and execution path; host-mapping helpers do not automatically provide every device-to-device visibility guarantee.
This gives us a concrete next milestone without introducing an automatic-selection pass first: explicitly requested reuse, compatible allocation placement, no transfer copy, preserved ordering and maintenance, and correct behavior when other consumers still need the original value.
purnima-nlp commentedon Nov 12, 2026
Thanks, this makes the next milestone much clearer.
One related piece that is already in progress is #25192 (
[Stream] Preserve reusable transfers during copy elision). That PR handles the elision side by keeping transfers that need reuse semantics instead of replacing the result with the source and erasing the transfer, while still allowing transfers that are provably unnecessary to fold away.Together with #25143 and the work in #25178 and HAL to runtime pluming work already merged, I think that leaves the remaining explicit
storage=reusepath mainly around connecting the allocation/lowering semantics end-to-end:should we prefer that remaining work to be handled together in one final PR for the explicit
storage=reusemilestone, or rather split the work further?I’m happy to follow whichever decomposition makes review easier. !! Thanks for the guidance !!