Repository navigation
[Stream] Lower command buffer flush and invalidate to HAL - #25178
purnima-nlp wants to merge 7 commits into
Conversation
|
I’ve expanded this PR to include the missing local-task backend support for The local-task block command buffer now records and executes cache-maintenance commands for both direct and indirect buffer references, with per-binding READ/WRITE access tracking and existing barrier-based ordering. Focused local-task tests pass across 1, 2, 4, and 8 workers, and the previously failing local-task E2E cases now pass, including:
This should address the |
| auto targetBinding = commandBufferMapping.resolveBinding( | ||
| op.getLoc(), op.getTarget(), adaptor.getTarget(), | ||
| adaptor.getTargetOffset(), adaptor.getTargetLength(), rewriter); | ||
| rewriter.replaceOpWithNewOp<IREE::HAL::CommandBufferFlushBufferOp>( |
There was a problem hiding this comment.
Could we also update the single-copy/fill fast path so it cannot bypass this new lowering?
matchSingleTransferOp in this file, lines 1243–1264 currently ignores stream.cmd.invalidate and stream.cmd.flush. If it finds one fill or copy, CmdExecuteOpPattern emits a queue operation and replaces the entire execute region at line 1322. The nested cache operations are therefore erased before the new patterns here get a chance to lower them.
I reproduced this with cache maintenance on a different buffer from the fill:
module {
util.global private @device : !hal.device
util.func public @cache_fast_path(%target: !stream.resource<transient>, %cache: !stream.resource<transient>) -> !stream.timepoint {
%size = arith.constant 16 : index
%c0 = arith.constant 0 : index
%c4 = arith.constant 4 : index
%value = arith.constant 7 : i32
%signal = stream.cmd.execute once on(#hal.device.affinity<@device>) with(%target as %capture: !stream.resource<transient>{%size}, %cache as %cache_capture: !stream.resource<transient>{%size}) {
stream.cmd.invalidate %cache_capture[%c0 for %c4] : !stream.resource<transient>{%size}
stream.cmd.fill %value, %capture[%c0 for %c4] : i32 -> !stream.resource<transient>{%size}
stream.cmd.flush %cache_capture[%c0 for %c4] : !stream.resource<transient>{%size}
} => !stream.timepoint
util.return %signal : !stream.timepoint
}
}Run:
iree-opt --iree-hal-conversion --cse \
--iree-hal-indirect-command-buffers=true repro.mlirThe output has a hal.device.queue.fill targeting the first buffer argument, but no hal.command_buffer.invalidate_buffer or hal.command_buffer.flush_buffer; the second buffer argument becomes unused. These operands can refer to unrelated allocations, so the fill cannot be assumed to perform the required cache maintenance on %cache. The same matcher handles a single stream.cmd.copy, so that path needs protection too.
A small conservative fix is to split the existing TypeSwitch case: flush/invalidate should make the single-transfer match fail, while discard/yield can still be ignored:
.Case<IREE::Stream::CmdInvalidateOp, IREE::Stream::CmdFlushOp>(
[](auto) { return false; })
.Case<IREE::Stream::CmdDiscardOp, IREE::Stream::YieldOp>(
[](auto) { return true; })The surrounding matcher already returns nullptr when a case returns false, so this keeps the normal command-buffer path and allows the new cache-maintenance patterns to execute.
Please add negative fast-path tests for invalidate → fill → flush and invalidate → copy → flush, including unrelated cache/transfer buffers, and retain the cache-only case. I checked the latter: without the fill, both HAL cache operations and queue execution remain. The existing cmd_ops.mlir passes, but does not cover this shortcut. This matcher predates the PR; updating it is necessary for the newly enabled cache-maintenance lowering to cover these regions.
| auto targetBinding = commandBufferMapping.resolveBinding( | ||
| op.getLoc(), op.getTarget(), adaptor.getTarget(), | ||
| adaptor.getTargetOffset(), adaptor.getTargetLength(), rewriter); | ||
| rewriter.replaceOpWithNewOp<IREE::HAL::CommandBufferInvalidateBufferOp>( |
There was a problem hiding this comment.
Before enabling flush/invalidate lowering unconditionally for every target, could we establish the supported backend and memory/coherence cases?
The new local_task command recording and execution support addresses the queued CPU path, including indirect bindings. However, at this head, native GPU command-buffer vtables still do not provide .flush_buffer / .invalidate_buffer callbacks. Examples include:
- CUDA stream command buffer and CUDA graph command buffer.
- HIP stream command buffer and HIP graph command buffer.
- Vulkan command buffer.
The common HAL entry points explicitly return IREE_STATUS_UNIMPLEMENTED when these callbacks are missing: flush at runtime/src/iree/hal/command_buffer.c:516–524, and invalidate at lines 545–554.
The path this exposes is:
stream.cmd.flush / invalidate in a surviving execution region
→ hal.command_buffer.flush_buffer / invalidate_buffer
→ existing VM/runtime call
→ selected native GPU command buffer has no callback
→ UNIMPLEMENTED
Previously the Stream operation was erased. This PR makes it reach that runtime path, so adding local-task support alone does not justify enabling it universally. Cache-only regions, and regions containing dispatches or multiple data-transfer commands, can reach the command-buffer path independently of the single-transfer shortcut discussed separately.
Also, the new local-task execution uses mapped host-memory flush/invalidate helpers. That is appropriate for those mappings, but it does not establish generic GPU cache or ownership semantics for all device-visible buffers. Source/destination accessibility, coherence, execution ordering, and the actual allocation must determine whether maintenance is required and which mechanism can perform it.
Suggested scope for this PR: restrict activation to supported target/memory paths until the remaining backends have defined behavior, or provide that backend behavior before unconditional activation. A no-op is appropriate only when coherence/visibility guarantees make maintenance unnecessary; required non-coherent maintenance must not be silently discarded. Deferred recording also needs its eventual execution backend to support the operation.
Please add coverage for the supported/unsupported backend boundary, coherent no-maintenance cases, and required non-coherent maintenance. This concern follows from the source and missing callbacks; I have not executed a native GPU reproduction. The new local-task tests are useful coverage, but they do not exercise that path.
|
@Manewing thanks a lot for your feedback and guidance, im grateful, I investigated extending the remaining GPU backends rather than limiting this to local-task. Vulkan is the most promising backend because it already has real non-coherent mapped-memory maintenance through A correct Vulkan implementation needs something like:
The existing queue machinery cannot safely express that today. Pre-submitting segment B behind a private gate creates a failure problem: if the host cache action fails, opening the gate executes work that should have been cancelled, while leaving it closed can prevent the queue from draining during shutdown. Delaying submission of B until the host action succeeds avoids that, but then the queue needs a way to reserve B's position so later submissions cannot overtake it. That becomes a queue-owned ordered host-action/submission chain with cancellation semantics, which is broader backend scheduling work rather than a small command-buffer callback addition. CUDA and HIP have the same general execution-time issue, with fewer directly usable cache-maintenance primitives for the relevant shared-memory cases. Given that, I don't think unconditional activation on all HAL backends is appropriate in this PR. One option that seems cleaner than making StreamToHAL backend-specific would be to introduce a HAL capability for command-buffer cache maintenance. The compiler/runtime path that creates these operations could use that capability to avoid selecting/emitting a maintenance-dependent path for unsupported backends, while keeping the actual Stream-to-HAL lowering generic: The capability would tell whether the selected execution path can correctly honor the HAL cache-maintenance semantics. Today that would be supported by local-task and unsupported by CUDA/HIP/Vulkan until their backend behavior is defined. I suppose this also keeps the zero-copy path well-defined:
Would you think we should get into introducing such a HAL capability in this PR to restrict activation to supported paths, or would you rather keep that capability/gating work with the later storage-reuse scheduling changes and restrict this PR another way? A few source references that led me to that conclusion:
I also prototyped recording these operations and splitting Vulkan native replay at the cache-action boundaries. That part is straightforward; the remaining issue is queue-side ordering/cancellation of successor segments, which is what pushed me toward suggesting an explicit HAL capability boundary rather than unconditional activation. |
|
@purnima-nlp thank you for your investigation. Trying to make sense of your findings and looking forward (see also #24930 (comment)) I suggest keeping the generic lowering and local-task implementation together in this PR. We do not need to wait for automatic storage-reuse selection or add a capability query. There is one compiler shortcut to fix alongside the lowering. matchSingleTransferOp currently ignores flush/invalidate, so it can replace: copy → flush with just a queue copy, dropping the flush. When either maintenance operation remains, keep the command-buffer path. This also applies when the copy and maintenance target different buffers. Please add tests for copy, fill, and maintenance-only regions. The matcher change in #24962 is a useful starting point, but needs to cover invalidate as well as flush; the HAL plumbing already landed in #24945. We also need to handle the maintenance commands that existing copy paths will now send to backends. This is relevant even before anything selects storage=reuse. Returning success is fine when the backend’s memory and synchronization guarantees already satisfy the operation, for example, when no additional cache action is needed for coherent memory. That should be a documented implementation, rather than a TODO that silently accepts unsupported maintenance. Ordinary compiler staging allocations already require host-coherent memory, which helps keep this work bounded. For those paths, check whether existing synchronization provides the required visibility or whether a native memory barrier is needed. Coherence alone does not replace synchronization. We do not need to implement general Vulkan host-action scheduling in this PR. Cases that genuinely require unsupported execution-time cache maintenance should fail explicitly. Checks involving indirect bindings must use the actual submitted buffer. I think we should focus here on preserving maintenance during lowering, executing it correctly on local-task, and keeping existing supported copy paths working on the affected backends. Compiler tests should cover the shortcut above; runtime tests should cover producer waits, replay, indirect bindings, ranges, and failure propagation. The broader shared-storage allocation and value-lifetime cases remain part of #24930. |
|
@Manewing thanks again for the detailed guidance. I’ve now covered the remaining scope you called out for this PR. The compiler shortcut is fixed so For the GPU backends, I added explicit cache-maintenance behavior:
I added Vulkan queue CTS coverage for the runtime cases you listed:
The existing Vulkan command-buffer test already covers indirect range resolution and Local validation:
This should now cover the producer-wait, replay, indirect-binding, range, and failure-propagation cases you requested, while leaving the broader shared-storage allocation/value-lifetime work in #24930. |
| IREE_HAL_VULKAN_CACHE_MAINTENANCE_FLUSH | ||
| ? VK_ACCESS_2_MEMORY_READ_BIT | ||
| : (has_memory_visibility | ||
| ? VK_ACCESS_2_MEMORY_READ_BIT | |
There was a problem hiding this comment.
Nested ternary operators are unreadable.
Please make sure to self-review and understand the code that you are modifying/submitting. You have to vouch for all changes that you are making - If you don't feel comfortable modifying a component, don't feel pressured to do so :)
There was a problem hiding this comment.
Thank you for pointing this out, and for taking the time to review the changes so carefully. I went back and cross-checked the affected paths again.
This PR touches quite a few parts of the codebase, so I may have overlooked a few readability details even when the underlying logic was right. Sorry about that.
And please don’t worry about me feeling pressured — I’m genuinely very excited about this issue, and I’m really grateful for your guidance and the time you’re putting into helping me improve. Please feel free to set high expectations for me; I’m happy to put in the work and learn as much as I can from this.
| : IREE_HAL_MEMORY_ACCESS_READ, | ||
| ref.offset, length, &mapping)); | ||
| iree_status_t status = cmd->header.opcode == IREE_HAL_CMD_FLUSH | ||
| ? iree_hal_buffer_mapping_flush_range( |
| ConversionPatternRewriter &rewriter) const override { | ||
| // TODO(benvanik): HAL command buffer op for invalidate. | ||
| rewriter.eraseOp(op); | ||
| auto commandBufferMapping = mapping->lookupCommandBufferFor(op); |
There was a problem hiding this comment.
breaking change between compiler & runtime, this need release alignment and version update
| iree_hal_command_buffer_t* base_command_buffer, | ||
| iree_hal_buffer_ref_t target_ref) { | ||
| return iree_hal_hip_graph_command_buffer_cache_maintenance( | ||
| target_ref, "invalidate_buffer"); |
There was a problem hiding this comment.
why are you passing a string here?
There was a problem hiding this comment.
It was only being used to distinguish the operation name in the diagnostic message; it did not affect the cache-maintenance behavior. I agree that passing a string makes that unclear, so I removed the argument and now use a common cache-maintenance diagnostic instead.
|
|
||
| #include "iree/base/threading/thread.h" | ||
| #include "iree/hal/drivers/local_task/block_builder.h" | ||
| #include "iree/hal/drivers/local_task/block_command_buffer.h" |
There was a problem hiding this comment.
I think there is no end-to-end test coverage for the CPU/local device reading a (non-)coherent buffer written by another device.
There was a problem hiding this comment.
Yes, you right — that exact E2E case was missing.
I added a Vulkan queue test for device write then host visibility then queue completion then CPU mapping/invalidate then CPU read on an actual non-coherent host-visible allocation. The test verify that the returned memory type is non-coherent or not and skips when the device does not expose a suitable memory type.
so, On my local Vulkan device it skips for that reason, while the rest of the cache-maintenance queue tests pass.
There was a problem hiding this comment.
sorry I was a bit imprecise here. end-to-end test in the sense of MLIR being compiled and executed, like iree-run-module-multi.mlir to test if this "feature", as a whole, work as intended.
| @@ -96,6 +96,12 @@ typedef struct iree_hal_vulkan_command_dispatch_t { | |||
| iree_hal_dispatch_flags_t flags; | |||
There was a problem hiding this comment.
fixme in command_buffer.c needs to be updated
// FIXME: Not all command-buffer backends implement flush_buffer yet.
// Stream-to-HAL lowering remains disabled until backend execution semantics
// are supported.
| ConversionPatternRewriter &rewriter) const override { | ||
| // TODO(benvanik): HAL command buffer op for flush. | ||
| rewriter.eraseOp(op); | ||
| auto commandBufferMapping = mapping->lookupCommandBufferFor(op); |
There was a problem hiding this comment.
HAL module version needs update for the imports, which in turn requires release coordination
Add minimum_version = 8 to both imports (hal.imports.mlir:273), and make IREE_HAL_MODULE_VERSION_0_8 the latest (module.c:46).
| const iree_hal_vulkan_command_t* command) { | ||
| const iree_hal_vulkan_command_execution_barrier_t* execution_barrier = | ||
| iree_hal_vulkan_command_execution_barrier_payload(command); | ||
| if (execution_barrier->cache_maintenance_kind != |
There was a problem hiding this comment.
can you explain when exec barriers will be inserted into the cmd q for cache maintenance, and where in the command q they will be "located"? since execution order/changes inside the command buffer is actually un-observable for any consumer, some of this might not be necessary.
There was a problem hiding this comment.
The cache-maintenance exec barrier is recorded at the exact position of the HAL flush in the command sequence. During native replay, it becomes a vkCmdPipelineBarrier2 at that same point in the Vulkan command buffer, so only writes before the flush are in its source scope.
For coherent flush, the barrier provides device-write to HOST_READ visibility. Queue completion orders the later CPU access, but does not itself make the preceding device writes host-visible, so I kept the barrier and made the destination explicitly VK_ACCESS_2_HOST_READ_BIT.
For coherent invalidate, no native barrier is emitted; replay only resolves/validates the buffer, since the producer/submission synchronization already orders the host-write to device path.
There was a problem hiding this comment.
"The cache-maintenance exec barrier is recorded at the exact position of the HAL flush in the command sequence."
- so if there are multiple buffers requiring a flush, there will be multiple barriers?
- is there any attempt in the compiler to group/move the "cache maintenance" to the beginning/end of command buffers?
There was a problem hiding this comment.
"The cache-maintenance exec barrier is recorded at the exact position of the HAL flush in the command sequence."
- so if there are multiple buffers requiring a flush, there will be multiple barriers?
- is there any attempt in the compiler to group/move the "cache maintenance" to the beginning/end of command buffers?
Yes — currently each surviving HAL flush produces its own Vulkan barrier.
I checked the compiler side and there isn’t a pass today that groups or moves these cache-maintenance ops to command-buffer boundaries. I kept the one-to-one lowering because moving a flush across intervening commands could change which writes it covers.
Grouping adjacent compatible flushes could be the next optimization, for now i did this much only, if you allow will analyze it.
| } iree_hal_vulkan_command_dispatch_t; | ||
|
|
||
| typedef enum iree_hal_vulkan_cache_maintenance_kind_e { | ||
| IREE_HAL_VULKAN_CACHE_MAINTENANCE_NONE = 0, |
| "Vulkan execution-time cache maintenance for non-coherent memory " | ||
| "is unsupported"); | ||
| } | ||
| // Coherent host writes need no cache operation. Submission waits order the |
There was a problem hiding this comment.
what submission? vkQueueSubmit?
"Coherent host writes need no cache operation." does not follow from "Submission waits order the producer before later device reads.". vk semaphore waits do not guarantee host cache coherence
There was a problem hiding this comment.
Agreed — I mixed coherence with ordering there because I was describing the whole host→device path in one comment. I updated it to separate the two: HOST_COHERENT avoids explicit cache invalidation, while ordering is handled by synchronization.
|
|
||
| CTS_REGISTER_TEST_SUITE(VulkanQueueDeallocaTest); | ||
|
|
||
| class VulkanQueueCacheMaintenanceTest : public CtsTestBase<> { |
There was a problem hiding this comment.
is there coverage of flush/invalidate in the non-driver-specific CTS? .... based on the proportion/number of changes in the drivers IMO runtime changes should be a separate PR
There was a problem hiding this comment.
There wasn’t any generic command-buffer CTS coverage before. so, I added coherent flush_buffer and invalidate_buffer cases to the shared command-buffer copy CTS, so now these paths are exercised independently of the Vulkan-specific tests.
| iree_hal_command_buffer_t* base_command_buffer, | ||
| iree_hal_buffer_ref_t target_ref) { | ||
| return iree_hal_cuda_graph_command_buffer_cache_maintenance( | ||
| target_ref, "invalidate_buffer"); |
| } | ||
| }; | ||
|
|
||
| TEST_P(VulkanQueueCacheMaintenanceTest, DeviceWriteToNonCoherentHostRead) { |
There was a problem hiding this comment.
isn't non-coherent not supported for Vulkan?
There was a problem hiding this comment.
Yes, you're right. Adding that test was a mistake on my side. It created a non-coherent Vulkan buffer, but then validated it through the existing mapped-buffer invalidate API, not through the new command-buffer flush_buffer / invalidate_buffer path.
Since command-buffer cache maintenance for non-coherent Vulkan memory is intentionally UNIMPLEMENTED in this PR, the test was not actually covering the feature being added and was therefore misleading. I removed it.
|
|
||
| #include "iree/base/threading/thread.h" | ||
| #include "iree/hal/drivers/local_task/block_builder.h" | ||
| #include "iree/hal/drivers/local_task/block_command_buffer.h" |
There was a problem hiding this comment.
sorry I was a bit imprecise here. end-to-end test in the sense of MLIR being compiled and executed, like iree-run-module-multi.mlir to test if this "feature", as a whole, work as intended.
| sizeof(kPattern), IREE_HAL_FILL_FLAG_NONE)); | ||
| const iree_hal_memory_barrier_t host_read_barrier = { | ||
| IREE_HAL_ACCESS_SCOPE_TRANSFER_WRITE, IREE_HAL_ACCESS_SCOPE_HOST_READ}; | ||
| IREE_ASSERT_OK(iree_hal_command_buffer_execution_barrier( |
There was a problem hiding this comment.
why are there manually inserted barriers here?
There was a problem hiding this comment.
My bad, That barrier was only part of the non-coherent readback test I had added. After tracing the test more carefully, I realized it was exercising the existing mapped-buffer invalidate path rather than the new command-buffer flush_buffer / invalidate_buffer path.
Since command-buffer cache maintenance for non-coherent Vulkan memory is intentionally unsupported in this PR, I removed that test entirely. The manually inserted barrier is therefore gone as well.
There was a problem hiding this comment.
I'm sorry, but I don't get the feeling that this is mergeable in its current state. I appreciate the effort, but the change appears to be touching too many areas for anyone to have the required expertise to author or review as a unit, and I believe it should thus be split & reconsidered if some parts would be better addressed in Issues. The scope of the PR has also significantly increased since its creation and no longer fits the scope indicated by the title or description, which is a good indication that it has grown too big.
You might also want to check the [contribution guidelines] (https://iree.dev/developers/general/contributing/#ai-tool-use) again.
Signed-off-by: purnima <[email protected]>
Signed-off-by: purnima <[email protected]>
Signed-off-by: purnima <[email protected]>
Signed-off-by: purnima <[email protected]>
Signed-off-by: purnima <[email protected]>
Signed-off-by: purnima <[email protected]>
Signed-off-by: purnima <[email protected]>
17373cd to
f7799bd
Compare
This implements step 4 of #24930.
Lowers
stream.cmd.flushandstream.cmd.invalidateto the corresponding HAL command buffer operations instead of erasing them during Stream-to-HAL conversion.stream.cmd.flushnow lowers to:hal.command_buffer.flush_bufferand
stream.cmd.invalidatelowers to:hal.command_buffer.invalidate_bufferThe lowering resolves the target resource binding and preserves the byte offset and length of the original Stream operation.
The HAL command buffer flush/invalidate operations and their HAL-to-VM/runtime lowering are already available. This change connects the existing Stream cache-maintenance operations to that lowering path so they are preserved through Stream-to-HAL conversion instead of being dropped.
Updated
StreamToHAL/test/cmd_ops.mlirto check the flush/invalidate lowering and command ordering.test passes: