Skip to content

Multi-device Zero-Copy Path: Missing lowering for stream.cmd.flush/invalidate and zero-copy path #24930

Open

Description

@Manewing

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 (

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> {
. This lowers to IREE::HAL::CommandBufferCopyBufferOp which is sub-sequently lowered to the VM call here

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_range
  • iree_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 non-coherent memory this elision is not valid.

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

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

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

  1. added
    enhancement ➕
    on Sep 14, 2026
  2. changed the title [-]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[/+] on Sep 14, 2026
  3. purnima-nlp commented on Sep 16, 2026

    @purnima-nlp
    Contributor

    hey i have working on this already , may you assign it to me

  4. Manewing commented on Sep 21, 2026

    @Manewing
    ContributorAuthor

    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

  5. purnima-nlp commented on Sep 21, 2026

    @purnima-nlp
    Contributor

    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

    Yes I would love to contribute on this issue, let me see what's already implemented.
    I will comment soon on this

  6. devtbi commented on Sep 22, 2026

    @devtbi
    Contributor

    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.

  7. purnima-nlp commented on Sep 22, 2026

    @purnima-nlp
    Contributor

    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.

    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 copy vs alias earlier on the transfer seems cleaner than trying to infer it after allocation/scheduling.

    Would you prefer that hal.command_buffer.flush_buffer / invalidate_buffer be explicitly scoped/documented as mapped-memory cache maintenance only, with stream.cmd.flush/invalidate remaining 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 | alias to be carried on flow.tensor.transfer / stream.async.transfer, with topology used to derive it where possible, while coherence is resolved separately from buffer/memory properties?

  8. l0r3m1psum commented on Sep 27, 2026

    @l0r3m1psum

    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!

  9. purnima-nlp commented on Oct 7, 2026

    @purnima-nlp
    Contributor

    @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:

    • representing transfer kind (copy vs alias) earlier in Flow/Stream,
    • allocation planning so alias transfers reuse the same backing storage,
    • avoiding stream.cmd.copy for valid zero-copy transfers while preserving synchronization/cache maintenance,
    • or topology/coherence-based selection of the transfer path.

    I’m happy to pick one of these and keep the scope small to avoid overlapping with ongoing work.

  10. Manewing commented on Oct 20, 2026

    @Manewing
    ContributorAuthor

    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:

    • Unspecified/default: keep existing behavior
    • Copy: keep existing behavior (separate destination storage and copy of data)
    • Reuse: The result refers to the same buffer range as the source

    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:

    1. replace transfer result with source
    2. erase transfer

    We need to keep the transfer in case of reuse:

    1. mark transfer as reusing source storage
    2. keep the transfer and its result

    3. Adjust lowering in async-to-cmd

    applyAsyncTransferOp must omit stream.cmd.copy for 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!

  11. purnima-nlp commented on Oct 21, 2026

    @purnima-nlp
    Contributor

    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:

    • Unspecified/default: keep existing behavior
    • Copy: keep existing behavior (separate destination storage and copy of data)
    • Reuse: The result refers to the same buffer range as the source

    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:

    1. replace transfer result with source
    2. erase transfer

    We need to keep the transfer in case of reuse:

    1. mark transfer as reusing source storage
    2. keep the transfer and its result

    3. Adjust lowering in async-to-cmd

    applyAsyncTransferOp must omit stream.cmd.copy for 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!

    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.

  12. Manewing commented on Oct 21, 2026

    @Manewing
    ContributorAuthor

    @purnima-nlp sounds good, looking forward to the changes! :)

  13. Manewing commented on Nov 12, 2026

    @Manewing
    ContributorAuthor

    The original plan still looks right. The next step is to make an explicitly selected storage=reuse transfer 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:

    CPU writes buffer A
    allocate buffer B that the accelerator can access
    copy A into B
    perform any required cache maintenance
    accelerator reads B
    

    With compatible shared storage and storage=reuse, we want:

    allocate buffer A that both CPU and accelerator can access
    CPU writes A
    flush those writes if required
    accelerator reads the same range of A
    

    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=reuse therefore means updating the existing compiler machinery to:

    1. Make the transfer result refer to the same buffer range as its source.
    2. Avoid a separate destination allocation and omit the transfer copy.
    3. Keep the required flush/invalidate operations and the dependencies between producer and consumer.
    4. Preserve other consumers' values if a later operation updates the shared storage.

    That last point is easy to miss. Consider this illustrative tensor-level example:

    original = produce()
    shared = transfer(original, storage=reuse)
    updated = update(shared)
    consume(original)
    

    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 for update, 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:

    CPU writes finish → flush finishes → accelerator reads
    

    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.

  14. purnima-nlp commented on Nov 12, 2026

    @purnima-nlp
    Contributor

    The original plan still looks right. The next step is to make an explicitly selected storage=reuse transfer 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:

    CPU writes buffer A
    allocate buffer B that the accelerator can access
    copy A into B
    perform any required cache maintenance
    accelerator reads B
    

    With compatible shared storage and storage=reuse, we want:

    allocate buffer A that both CPU and accelerator can access
    CPU writes A
    flush those writes if required
    accelerator reads the same range of A
    

    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=reuse therefore means updating the existing compiler machinery to:

    1. Make the transfer result refer to the same buffer range as its source.
    2. Avoid a separate destination allocation and omit the transfer copy.
    3. Keep the required flush/invalidate operations and the dependencies between producer and consumer.
    4. Preserve other consumers' values if a later operation updates the shared storage.

    That last point is easy to miss. Consider this illustrative tensor-level example:

    original = produce()
    shared = transfer(original, storage=reuse)
    updated = update(shared)
    consume(original)
    

    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 for update, 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:

    CPU writes finish → flush finishes → accelerator reads
    

    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.

    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=reuse path mainly around connecting the allocation/lowering semantics end-to-end:

    • make the transfer result use the source storage/range,
    • avoid allocating separate destination storage,
    • omit the transfer copy,
    • preserve the required maintenance and producer/consumer ordering,
    • and handle cases where later mutation of the reused storage would otherwise change the value seen by existing consumers of the original result.

    should we prefer that remaining work to be handled together in one final PR for the explicit storage=reuse milestone, or rather split the work further?

    I’m happy to follow whichever decomposition makes review easier. !! Thanks for the guidance !!

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancement ➕

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions