Skip to content

[metal] Implement a Metal HAL driver - #12713

Merged
antiagainst merged 60 commits into
iree-org:mainfrom
antiagainst:metal-hal-pr
Jun 14, 2023
Merged

antiagainst merged 60 commits into
iree-org:mainfrom
antiagainst:metal-hal-pr

Conversation

@antiagainst

@antiagainst antiagainst commented Mar 22, 2023 •

Copy link
Copy Markdown
Member

This pull request resurrects the previously removed Metal
HAL driver due to HAL revamping. It now implements the
HAL driver using Objective-C, instead of Objective-C++
like previously. We also explicitly track resource lifetimes
and manage dependencies, following IREE explicitness.

Right now the following features are implemented:

  • HAL driver: device emulation, and some feature printing
  • HAL device: resource creation, kernel launches, and sync
  • HAL allocation: simple allocator without any caching or sub
    allocation (we expect common layer for those later)
  • HAL command buffer: one-shot command buffer, both
    direct and indirect dispatches
  • HAL executables: both compile to MSL and .metallib
  • HAL executable caches: just simple no op cache for now
  • HAL builtin executables: for filling/copying buffers
  • HAL semaphore: real async queue execute, but not
    stream-ordered allocation yet

The implementation right now assumes Metal3 devices.
It passes all existing CTS tests, end-to-end StableHLO
and TOSA op and model tests in tree for Apple M1
MacBook.

Fixes #4370

@antiagainst antiagainst added the hal/metal Runtime Apple Metal HAL backend label Mar 22, 2023
@antiagainst
antiagainst requested a review from ScottTodd March 22, 2023 00:13
@powderluv

Copy link
Copy Markdown
Contributor

Woah awesome. Time to try stable diffusion 😀

@antiagainst
antiagainst force-pushed the metal-hal-pr branch 6 times, most recently from 54b7dfd to 890d82d Compare March 26, 2023 17:16
@antiagainst
antiagainst force-pushed the metal-hal-pr branch 4 times, most recently from 47693aa to cf99485 Compare April 6, 2023 19:12
@antiagainst
antiagainst force-pushed the metal-hal-pr branch 4 times, most recently from ead5ff2 to 0d5318c Compare April 11, 2023 01:50
@antiagainst

antiagainst commented Apr 12, 2023 •

Copy link
Copy Markdown
Member Author

Listing some bigger questions/tasks mentioned in offline discussions:

General

  • Add documentation for Metal HAL driver
  • Perform refcount analysis using some tools to make sure consistency
  • Use IREE status macro for debug printing in runtime kernel compilation/loading (blocking)

Compiler

  • Use LLVM process launch utilities for calling offline metal toolchain
    • Allow using offline metal toolchain on non-Apple devices
  • Wire up and detect target platform from device configuration
  • Merge executables and support multiple entry point per executable (performance/breaking change)
  • Handle threadgroup size via specialization constant (breaking change)

HAL allocator / buffer

  • Support managed storage type better
    • Avoid doing iree_hal_device_transfer_range if possible for initial data (blocking/performance)
    • Make sure proper flush and invalidate (blocking/correctness)
    • Use IREE_HAL_BUFFER_COMPATIBILITY_LOW_PERFORMANCE for device local + host visible (blocking/performance)
  • Double check Metal CPU/GPU coherency guarantee for non-managed storage type (correctness)

HAL command buffer

  • Follow WebGPU command buffer segment management (blocking)
  • Check whether we have proper command buffer execution-only barrier support (blocking/correctness)
  • Avoid using MTLFence to sync when switching blit/compute encoders (blocking/performance)
    • Use a single MTLEvent object?
    • Avoid addCompletedHandler for releasing the MTLFence
  • Borrow fill buffer polyfill impl from WebGPU (performance)
  • Change command buffer update buffer impl to avoid doing allocations (blocking/performance)
  • Follow CPU HAL driver impl to handle push descriptor condensing and referencing (performance/breaking change)
  • Drop unnecessary validations in command buffer implementations (blocking/cleanup)

HAL device / queue

  • Support multiple queues for more concurrency cases (performance)
  • Use resource set for semaphore management in queue execute (blocking/performance)
  • Return okay status for queue flush (blocking/correctness)

HAL executable

  • Manage argument buffer in command buffers instead of during kernel compilation (blocking/correctness)

HAL semaphore

  • Use event pool to manage semaphore waits (performance)

HAL event

  • Delete HAL event impl via MTLFence and make it unimplemented
  • Rethink HAL event support
    • Using WebGPU tricks?

@powderluv

Copy link
Copy Markdown
Contributor

There are non Apple metal devices ?

Would it be ok to land this and address the issues listed? Or are they needed before landing (trying to get rid of moltenvk support in SHARK which only works on version 216.)

@antiagainst

Copy link
Copy Markdown
Member Author

There are non Apple metal devices ?

I was under the impression that Metal offline toolchain is only available on Apple platforms. Ben pointed out that they are also available on Windows. So we can also use them to do MSL to .metallib compilation on Windows; don't need to restrict to Apple platforms for the compilation there.

Would it be ok to land this and address the issues listed? Or are they needed before landing (trying to get rid of moltenvk support in SHARK which only works on version 216.)

Not blocking thus far. Just listing these relative major points so we don't forget them.

@antiagainst
antiagainst force-pushed the metal-hal-pr branch 2 times, most recently from 6d62849 to d22d684 Compare April 18, 2023 23:07
@antiagainst antiagainst added the codegen/spirv SPIR-V code generation compiler backend label Apr 21, 2023
@antiagainst
antiagainst force-pushed the metal-hal-pr branch 7 times, most recently from 08f7e5f to d65b254 Compare April 27, 2023 16:41
Unlike Vulkan, Metal adopts a multi-level command recording model--
memory/dispatch commands are not directly recorded into a command buffer;
rather, they must go through the additional level of blit/compute encoders.
IREE's HAL follows the flat Vulkan command buffer recording model, so we
have a mismatch here. Implementing IREE's HAL using Metal would require
switching encoders for interleaved memory and dispatch commands.
Additionally, certain IREE HAL API features do not have direct mapping in
Metal APIs, e.g., various forms of IREE HAL execution/memory barriers.
Translating them would require looking at both previous and next commands
to decide the proper mapping.

Due to these reasons, it's beneficial to have a complete view of the full
command buffer and extra flexibility during recording, in order to fixup
past commands, or inspect future commands.

Therefore, to implement IREE HAL command buffers using Metal, we perform
two steps using a linked list of command segments. First we create segments
(iree_hal_metal_command_buffer_prepare_* and iree_hal_metal_command_segment_create_*)
to keep track of all IREE HAL commands and the associated data, and then,
when finalizing the command buffer, we iterate through all the segments and
record their contents (iree_hal_metal_command_segment_record_*) into a
proper Metal command buffer . A linked list gives us the flexibility to
organize command sequence in low overhead; and a deferred recording gives
us the complete picture of the command buffer when really started recording.
These checks should not happen with compilers and runtime validation.
So just turn them into asserts.
This is in preparation of upcoming changes to use one single
device buffer for holding all argument buffers.
This commit switches the Metal HAL driver to use a staging buffer
for recording argument buffers and uploading buffer update source
data. This avoids creating lots of small-sized buffers like we
did previously, and avoids using command buffer completion callback
to handle their lifetime.
This makes the `iree_hal_metal_command_buffer_t` structure more
clear and readable.
This simplifies the logic for descriptor tracking in command
buffer states. Now we don't need to find the proper starting
index and sort.
We want to have `host_allocator` directly ahead of the `out_`
parameters.
For managed storage mode, we need to issue GPU commands to
explicitly make data visible to CPU. This would require
having a handle to a MTLCommandQueue. Instead of creating
a new one internally, give the queue to the buffer during
construction time.
This avoids the needs to create the buffer and clean it up later.
This saves us one level of indent to make the code easier to
follow.
Change it to follow device struct allocation, initialization, and
subresource creation. This way we can handle destruction on failures
better.
By this way, we can avoid tracking the current pipeline layout.
This avoids the potential refcount mismatches due to that we can
have command buffers created but never submitted and such.
This is an performance improvement over the previous case where
we always create a new command buffer for semaphore signaling.
MTLFunction and MTLComputePipelineState creation are common between
these two paths; so we can have one function for them.
This avoids mutating the `active_count` in the command buffer state.
We need to check the status and free the resource set if any
error happens.
We need to check the return status of resource set allcoation
and properly destroy the command buffer if any error happens.
@antiagainst
antiagainst enabled auto-merge June 14, 2023 04:23
@antiagainst
antiagainst disabled auto-merge June 14, 2023 04:40
@antiagainst
antiagainst enabled auto-merge June 14, 2023 04:41
@antiagainst
antiagainst merged commit 11388b8 into iree-org:main Jun 14, 2023
@antiagainst
antiagainst deleted the metal-hal-pr branch June 14, 2023 04:41
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

codegen/spirv SPIR-V code generation compiler backend hal/metal Runtime Apple Metal HAL backend

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Revive Metal runtime HAL backend with one written against the C HAL API

5 participants