Skip to content

Rewrite the HAL in C to enable external HAL drivers #4369

Closed

Description

@benvanik

The HAL - which originates from some internal google code several years old - was written in canonical google C++. To expose it via an API I added a C wrapper, however that resulted in us having a large island of C++ code (a lot of which depended on abseil due to its lineage) hidden behind a C API and made the goal of minimizing binary size and reducing per-call overhead ("as zero-cost as possible") impossible. It also meant that all HAL drivers would have to live in-tree as the C++ code could not be exposed as a stable API for which external HAL drivers could be authored against (and driver implementations would require abseil, etc). The layered C + C++ nature of the code led to a lot of duplication (every struct and enum, of which there are ~100), difficulty tracking allocations (std::allocator is... not great, and we didn't use it for the thousands of random C++ allocations that happen with inlinedvector/etc), and costly conversions (both in code size and runtime performance mapping lists of types around). In Apple environments it also required the use of Objective C++ (which is something that should really be avoided) and in others perpetually created an internal-vs-external tension about what-can vs. what-should be exposed via the API as some things, given their complex C++ nature, are nearly impossible by design to expose cleanly.

So, the HAL C + C++ layering is being inverted with C as the foundation and C/C++/etc as implementations. Rebasing on C turns "the HAL C API" into "the HAL" and allows us to both expose client consumption of the HAL and new HAL backend implementation via the same types. All duplicate types (and type/function signatures, etc) go away and the only places we need to add special handling is with any versioning we may want to support (as opposed to versioning crossed with language layer as before). We get more consistent behavior with the rest of the IREE code (proper iree_allocator_t usage), can remove abseil as a dependency (for almost everything but strings for the moment), and going forward can just have two places that need to be kept in sync: the HAL dialect in the compiler and the HAL API implementation in the runtime.

The core balance at play here is that every byte of binary size we add to an application, every byte of memory we allocate at runtime, and every extra bit of incremental processing we add per-call is a direct negative to users: that's fewer bytes of weights in their model (or fewer specialized/optimized generated kernels), less memory available for use by either the application or the model state, and fewer calls that can be made (equivalent to program complexity) while remaining in the same budgets. With the cost of the current HAL C/C++ sandwich and modern C++ implementations we'd have to have an exceptionally good reason to pay it - and we don't. This code is designed to be a shim layer to other APIs (metal/vulkan/etc) and basically just shuffle function pointers and data types around - we shouldn't require 100's of KB of binary and runtime memory consumption to literally call functions. It's also meant to be a stable interface that purposefully doesn't change much - not something heavily modified daily by dozens of people where some of the C++ features (RAII, etc) would be worth it. A bit of extra care and consideration on our part here is amplified as we are integrated into applications and then each of those ships fewer bytes to users over data connections, takes up less space on their device, has better models as the size/memory budgets weren't so constrained, etc. That said, for this particular kind of code that is exposed via C anyway this conversion is a readability and maintainability win: no duplication that requires structs/enums to stay in sync, no complex lifetime tracking changes between C/C++ when marshaling types, and consistency across the entire runtime (same types as VM, etc).

Major tasks

Initial rewrite PR

  • cull unused code/parameters/etc from the HAL
  • delete old iree/hal/*.h/cc code
  • excise DebugCaptureManager (pending rewrite)
  • split iree/hal/api.h into iree/hal/*.h types
  • implement vtable-based dispatch to allow external C HAL implementations
  • isolate remaining C++ to just the code touching strings for future rewriting
  • add executable loader mechanism to allow for shared CPU drivers
  • move iree/hal/vmla/op_module* to iree/modules/vmla/ (as was always suggested but hard to do)
  • replace existing iree/hal/host/ implementation with one based on the iree/task/ system (fixes Implement a CPU execution thread pool #49)
  • local task system semaphore and queue
  • rewrite iree/hal/vulkan/ to support the new C API - leave as C-like C++ (for now)
  • port (or wrap) emulated timeline semaphore to C
  • delete old CTS (pending rewrite)
  • delete Metal backend (pending rewrite)

Follow-on (soon(ish) after landing)

Future (Q1+)

Deferred Work

This is a big rewrite that was a long time coming (witnessed in the number of several-year-old internal TODO(b/)s I've been able to remove). Some things were left for future iterations involving more team-wide discussion/design/prioritization. The primary goal here was to get us to a foundation on which we want to build new things - not preserve 100% of the old things (even if they are useful in certain cases). The distinct advantage of the timing is that no one is shipping any of this code and when they do start shipping post-rewrite it'll be a much better experience and they'll never care about what existed before. We, as maintainers, can suck it up :)

Here's a few larger things we'll want to track/prioritize in Q1+:

Replace remaining C++ string code

The buffer view parsing/printing code (among others) uses a lot of abseil's string utils. Doing a rewrite requires adding string parser/builder support to iree/base/ at which time we'll be able to replace the C++ with pure C and eject abseil. After the initial rewrite very little of abseil remains (mostly absl::Span/absl::string_view-related) beyond a few TODOs (replacing VMA's mutex with our own, etc).

Replace remaining C++ vulkan types

Or at least the core ones (VkDeviceHandle and DynamicSymbols) - this would allow 3/4th of the Vulkan code to be pure C as those two types are used in every file and otherwise must be C++. Of course, then there's only a few things remaining in C++ (DescriptorSetArena, SerializingCommandQueue, etc) and it's probably worth ripping the bandaid for those and just completing the conversion.

Rework how CPU backends are handled in infra

Now that executable formats are orthogonal to the local (nee host) backend selected having top-level dylib and vmla drivers don't make sense. Instead the executable loader registry may just have different loaders registered and which are compiled in and available at runtime can be determined by flags. This is critical to allowing us to have heterogenous executables and is what will allow us to provide hand-authored fallbacks to code generation and enable static linkage of models where the "loaded executables" are just pointers to read-only data in the current binary. The complication is that the test infra currently assumes that dylib and vmla are drivers and the complex logic around test suite expansion and cmake/bazel configuration assumes the same. Going forward we should have a local driver available at runtime that loads and runs whatever it is compiled to support and compiler flags for whether the dylib/vmla/other executable loaders are registered. Tests must then compile for what they want to test only.

Replace DebugCaptureManager

DebugCaptureManager fits oddly into the HAL and we need to reevaluate whether we want it to exist or in what form. Vulkan and Metal exclusively use the DebugCaptureManager just to manage lifetime and start/stop capture when devices are created/destroyed. This capture control behavior is not useful as part of core and should be performed by the application - which may be a unit test starting/stopping capture on startup/shutdown or iree-run-module doing the same, or a user application that enables/disables capture at certain times, etc. Given the very specific behavior required for certain tools like Renderdoc not supporting multiple VkDevices being created in the same process we weren't doing a service by having nice generic interfaces that were invalid to use in many situations. Having an abstract DebugCaptureManager on the base types is of marginal utility as mixing managers between drivers doesn't make sense in a lot of cases (can't use the MTLCaptureManager with the Vulkan driver, etc) and could be served by a HAL API that modeled vkAcquireProfilingLockKHR instead. Since this is a debug-only feature and can be readily added back and applied as needed it's dropped for now. Going forward we should remove the dynamic injection of the capture managers and make them complier options (similar to the tracing enable compiler flag) so that we aren't keeping all the extra junk around in release builds where we don't want profiling.

Replace the CTS

The existing CTS was primarily just a skeleton and coded against the C++ types directly (it originated prior to the C API existing at all IIRC). There was also some functionality that was added to the core types to support the CTS where instead it should be a pure consumer of the API - for example, lifetime hacks that made their way into the Vulkan driver that we must not expose to users. Going forward having a test suite written against the HAL API is incredibly valuable but we'll want to approach it with fresh eyes with the new code and ensure we are layering correctly.

Replace the Metal backend

The Metal backend is too high of a tax right now to maintain through the rewrite. When we end up on the other side we'll need to rework it to use plain Objective C (instead of Objective C++) anyway and since it was not completed was going to start creating problems regardless of the rewrite (events/push constants/async behavior/etc were all missing or partial, preventing compiler features using them). I have a branch showing a partially-converted version that can be used as a base and starting from a fresh C implementation with that as a reference should make things pretty fast to finish up. Going forward we'll want to ensure that backends we add in-tree are ones we can support and that experimental backends are added under experimental/ first (enabling that is one of the reasons for this rewrite!). Since we've got our hands full with Vulkan/SPIR-V for the next quarter or two and no plans for anything that would ship using the backend it's safe to leave it in limbo for now.

Replace the dylib loader with the iree_hal_executable_library_t interface

iree/hal/local/loaders/legacy_library_loader.h contains the existing dylib implementation and system_library_loader.h is a partial implementation for the new iree_hal_executable_library_t interface that will replace it. The system library loader will allow us to avoid the flatbuffer and get the interface from dylibs directly which enables split files (model flatbuffer + one or more .so/.dll/.dylib files on the file system) - this will remove our temp file shenanigans and make deployment much more flexible. We can still support the dylib-in-memory but can do so via memfds and other mechanisms. Once we are switched over (the compiler generates the libraries and the runtime loads them from memory or files) we can add the static_library_loader.h that can allow for .o files produced by the compiler to be directly linked into the application binary and allow for efficient single-file deployments.

Activity

  1. added
    runtime
    hal/vulkan
    hal/metal
    yolo
    hal/cpu
    hal/api
    on Jan 4, 2021
  2. added this to the milestone on Jan 4, 2021
  3. benvanik commented on Jan 6, 2021

    @benvanik
    CollaboratorAuthor

    I decided not to use it for efficiency reasons, but I did mock up a C++ interface that sits on top of the HAL C API for defining drivers. Until things stabilize I don't want to support it but having bindings/cc/hal/ with this would make adding new external out-of-tree drivers easier for people who want to make that tradeoff. Preserving here in case we decide to use it.

    https://gist.github.com/benvanik/f5a8ff4928f58572882669dd92caced4

  4. 23 remaining items

  5. added
    platform/generic 🔩
    on Apr 18, 2021
  6. benvanik commented on Jun 6, 2022

    @benvanik
    CollaboratorAuthor

    Closing this tracking issue as the HAL C rewrite was finished. There are separate issues filed for cleaning up the last bits of Vulkan and improving configuration.

  7. moved this to Done in IREEon Jun 27, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Labels

hal/apihal/cpuhal/metalhal/vulkanplatform/generic 🔩runtimeyolo

Type

No type

Projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions