Skip to content

Add device topology infrastructure to HAL - #23573

Merged
benvanik merged 12 commits into
mainfrom
users/benvanik/hal-topology
Feb 25, 2026
Merged

benvanik merged 12 commits into
mainfrom
users/benvanik/hal-topology

Conversation

@benvanik

Copy link
Copy Markdown
Collaborator

Multi-device scheduling requires knowing how devices relate to each other: can device A wait on device B's semaphores natively, or does it need to import a handle? Can it read B's buffers directly, or must it issue a DMA transfer? What's the relative cost? Today the HAL has no way to answer these questions — every cross-device interaction is handled ad-hoc by the caller with no systematic way to discover capabilities or make cost-based placement decisions.

This PR adds a topology matrix to the HAL that encodes directional device relationships as packed edge descriptors. The matrix is built once during device group creation, is immutable thereafter, and supports lock-free concurrent queries from any thread.

Edge design

Each edge is a 128-bit descriptor split into two 64-bit words optimized for different access patterns:

  • Scheduling word (lo) — read on every placement decision. Contains interop modes (wait/signal/buffer-read/buffer-write), 16-bit capability flags, five 4-bit cost metrics (wait, signal, copy, latency class, NUMA distance), and a 3-bit physical link class. This is what the scheduler reads in the nanosecond path.

  • Interop word (hi) — read during resource import/export negotiation. Contains four 8-bit handle type bitmasks (semaphore import/export, buffer import/export) covering platform-specific sharing mechanisms from POSIX fd through RDMA memory regions. This is the microsecond path.

The split lets iree_hal_resource_origin_t (embedded in every semaphore and buffer) cache only the 8-byte scheduling word for ultra-fast compatibility checks, while the full 128-bit edge lives in the topology matrix for the rare import/export negotiation path.

Interop mode semantics

The 2-bit interop modes encode what the scheduler must do to make a resource usable on the destination device:

  • NATIVE — directly accessible via load/store. No action needed. Requires PEER_ADDRESSABLE (mapped BARs, unified memory).
  • IMPORT — import an external handle, then directly usable.
  • COPY — issue a transfer command. Covers both P2P DMA (direct device-to-device, low cost) and host-staged transfers (high cost). The copy_cost, link_class, and P2P_COPY capability flag distinguish the mechanism.
  • NONE — not possible.

This distinction matters because P2P DMA capability (the DMA engine can copy between devices) does not imply load/store addressability (shaders can access remote memory). Conflating them would cause the scheduler to reference a buffer directly in a dispatch when only DMA transfer is available.

Edge construction

Edges are computed in two phases: a base edge from device capabilities (driver names, UUIDs, handle type intersections, capability flag propagation, NUMA distance) and an optional driver-specific refinement pass. The base computation detects same-physical-device (cross-driver same-GPU via UUID matching), aliased devices (same-driver same-handle), and derives interop modes from handle type intersections. Drivers can then refine edges with hardware-specific knowledge (e.g., querying NVLink topology, Infinity Fabric link widths).

Platform topology queries

NUMA distance computation and CPU topology queries are factored into platform-specific backends (sysfs on Linux, IOKit on macOS, Win32 NUMA APIs, conservative fallback) so the core topology code stays platform-independent.

Where this is going

The topology matrix is the foundation for:

  • Automatic multi-device scheduling — the scheduler uses edge costs to decide where to place operations and how to move data between devices, replacing today's manual device selection.
  • RDMA and distributed execution — the handle type bitmasks and FABRIC link class support iree/net and iree/hal/remote work for cross-machine inference.
  • Device group creation — the topology pointer in device_topology_info_t will be populated by the device group, giving every device a path to query costs against any peer.
  • Resource compatibility fast-path — the cached scheduling word in resource_origin_t enables 1-3ns "can I use this buffer/semaphore?" checks without touching the topology matrix.

@benvanik
benvanik requested a review from AWoloszyn February 24, 2026 21:58
@benvanik benvanik added the hal/api IREE's public C hardware abstraction layer API label Feb 24, 2026
benvanik and others added 11 commits February 24, 2026 14:11
This will definitely get some iteration as we try to implement things -
this is heavily forward-looking at implementations we don't yet have
and refactoring we have yet to do.

This will be used in various places to make scheduling and placement
decisions, as well as being accessible for providing information to
HAL users (whether the compiler querying dynamic information or
pass-through API wrappers that need to satisfy queries).


Co-Authored-By: Claude <[email protected]>
…gy vtable into all HAL drivers.

Three logical changes combined because they share file-level dependencies
that prevent clean commit splitting without interactive staging:

1. sysfs extraction: Move file I/O and parsing utilities from
   task/topology_sysfs.c into base/internal/sysfs.{c,h} so they can be
   shared by both the task topology code and the new platform topology
   queries. task/topology_sysfs.c now includes the shared header instead
   of carrying its own copy.

2. platform_topology: New hal/utils/platform_topology.{c,h} providing
   cross-platform NUMA distance and PCIe topology queries (sysfs on
   Linux, stubs for Darwin/Windows/fallback). Uses the same
   platform-guard pattern as iree/task/topology_{sysfs,fallback}.c.

3. HAL device vtable: Add query_capabilities, topology_info, and
   refine_topology_edge methods to iree_hal_device_vtable_t. All drivers
   (null, local_sync, local_task, vulkan, cuda, hip, metal, amdgpu)
   implement the new vtable entries. The AMDGPU implementation queries
   real HSA properties (UUID, NUMA node, DMA-BUF support). Dispatch is
   unconditional (no NULL-checking fallbacks).

Also fixes:
- IREE_LIBHSA() wrapper missing on two iree_hsa_agent_get_info calls
  in the new AMDGPU query_capabilities implementation.
- Missing dep on device:headers in amdgpu/util:device_library_test.

Co-Authored-By: Claude <[email protected]>
The struct contains a uint64_t (8 bytes) followed by a uint32_t (4 bytes),
which pads to 16 bytes due to 8-byte alignment. The comment was inaccurate.

Co-Authored-By: Claude <[email protected]>
…s-validated review.

- Handle type intersections were reversed: for a directed edge src→dst, the
  import_types should be src_exports ∩ dst_imports (not dst_exports ∩ src_imports).
  All 4 handle type computations (semaphore import/export, buffer import/export)
  were computing the wrong direction.
- SAME_RUNTIME_DOMAIN capability flag was OR'd directly into the edge's wait_mode
  bits (bits 0-1) instead of being accumulated in the capability_flags field
  (bits 24-34). The flag was permanently lost when set_capability_flags overwrote
  the field.
- NUMA distance was calculated as abs(node_a - node_b) which treats node IDs as
  coordinates. NUMA node IDs are arbitrary logical handles. Now queries actual
  SLIT table distances via iree_hal_platform_query_numa_distance() and normalizes
  from the SLIT scale (10=same, 20=1hop, ...) to the edge's 0-15 scale.

Also exports topology_builder.h through api.h (it contains public API functions
marked IREE_API_EXPORT) and fixes test includes to go through api.h to satisfy
Bazel layering_check.

Co-Authored-By: Claude <[email protected]>
The scheduling word (lo) holds modes, capability flags (expanded from
11 to 16 bits), cost metrics, and link class for nanosecond-path
placement decisions. The interop word (hi) holds handle type bitmasks
(expanded from 4 to 8 bits per field) for microsecond-path resource
import/export negotiation.

resource_origin_t stays 16 bytes by caching only the scheduling word.

New handle types: RDMA_MR, SHM, METAL_IOSURFACE, ANDROID_HARDWARE_BUFFER.
New capability flags: REMOTE_DMA, SHARED_VIRTUAL_ADDRESS.
Typed word parameters (scheduling_word_t, interop_word_t) for API clarity.

Co-Authored-By: Claude <[email protected]>
…ing.

The boolean compatibility bitmaps (can_wait_from, etc.) answer "can I?"
but not "at what cost?" Adding a const pointer to the immutable topology
matrix lets the scheduler query the full 128-bit edge between any two
devices for cost metrics, latency classes, and handle type negotiation.

NULL for standalone devices not in a topology group. Non-NULL when the
device group populates it during device creation.

Adds iree_hal_device_topology_query_edge() convenience function that
handles NULL/mismatched-topology checks and returns the full edge.

Co-Authored-By: Claude <[email protected]>
P2P_COPY means the DMA engine can copy between devices, but does not
guarantee load/store addressability. A scheduler seeing NATIVE mode
might reference the buffer directly in a dispatch, which could fault
if only DMA access is available (e.g., PCIe P2P without large BAR).

Adds IREE_HAL_DEVICE_CAPABILITY_PEER_ADDRESSABLE to distinguish
load/store accessible P2P (NVLink large BAR, unified memory) from
DMA-only P2P (basic PCIe). Only PEER_ADDRESSABLE yields NATIVE mode;
P2P_COPY alone now correctly results in COPY mode with lower cost
(5 vs 9-13) to reflect the direct device-to-device DMA path.

Clarifies COPY mode docs: covers both P2P DMA and host-staged
transfers, distinguished by copy_cost, link_class, and P2P_COPY flag.

Co-Authored-By: Claude <[email protected]>
When two iree_hal_device_t instances wrap the same underlying driver
object (e.g., application creates two HAL devices for one GPU),
from_capabilities now detects the aliasing via matching
driver_device_handle and returns a self-edge (zero-cost NATIVE).

Previously, aliased devices at different topology indices would get
cross-device edges with non-zero costs, even though they share all
resources and can interoperate as if they were the same device.

Co-Authored-By: Claude <[email protected]>
The vtable function pointers for state_process and state_finalize were
missing IREE_RESTRICT on out_consumed/out_written, while the
implementing functions all had it. MSVC C4113 warns on the signature
mismatch when assigning to the vtable.

Co-Authored-By: Claude <[email protected]>
MSVC requires /std:c++20 for C99 designated initializers (.field=value).
Switch to the /*field=*/value pattern which works everywhere.

Co-Authored-By: Claude <[email protected]>
@benvanik
benvanik force-pushed the users/benvanik/hal-topology branch from 47ed7f1 to 21d2681 Compare February 24, 2026 22:12
…ementations.

The vtable now has IREE_RESTRICT on out_consumed/out_written, so all
implementing functions must match. Previously only replace.c and
regex_replace.c had the qualifier; the remaining 12 normalizers were
missing it, causing MSVC C4113 warnings.

Co-Authored-By: Claude <[email protected]>
@benvanik
benvanik marked this pull request as ready for review February 25, 2026 00:54
@benvanik
benvanik enabled auto-merge (squash) February 25, 2026 00:56
@benvanik
benvanik disabled auto-merge February 25, 2026 00:56
@benvanik
benvanik enabled auto-merge (squash) February 25, 2026 00:56
@benvanik
benvanik disabled auto-merge February 25, 2026 00:57
@benvanik
benvanik merged commit e0b5919 into main Feb 25, 2026
56 of 60 checks passed
@benvanik
benvanik deleted the users/benvanik/hal-topology branch February 25, 2026 00:57
benvanik added a commit that referenced this pull request Feb 25, 2026
The topology matrix from #23573 needs an owner with a clear lifetime
contract. Today devices are passed to the HAL module as a flat array —
there is no object that retains the devices, owns the topology, and
guarantees the topology pointer remains valid for the duration of
execution. Every device holds a raw pointer to the topology it was
assigned, so if the topology is freed while devices are still alive,
those pointers dangle.

`iree_hal_device_group_t` is that owner. It takes already-created
devices, builds the immutable topology matrix from their capabilities,
pushes topology info into each device, and retains all of them. The
group's lifetime brackets the devices': whoever holds the devices
long-term (the HAL module, the CTS harness, a Python session) retains
the group, and the group retains the devices, so the topology pointer in
each device is guaranteed valid.

### Creation API

The builder pattern matches the topology builder it wraps:
stack-allocate, add devices, finalize. Finalize is a consuming operation
— it queries capabilities from all devices, computes edge descriptors,
calls driver-specific refinement for same-driver pairs, builds the
topology matrix, assigns topology info into each device via the new
vtable method, and produces the immutable group. The builder is zeroed
after finalize (whether it succeeds or fails) and cannot be reused.

For the common single-device case (7 of 9 callers),
`iree_hal_device_group_create_from_device` wraps the builder sequence
into a one-liner.

### `assign_topology_info` vtable method

Devices need to receive their topology info after the matrix is built —
the topology doesn't exist yet when the device is created, and the
device's index in the matrix isn't known until group creation. This is a
new vtable method on `iree_hal_device_t` that the group calls during
finalize. All existing driver implementations (local-sync, local-task,
CUDA, HIP, Vulkan, Metal, AMDGPU, null) store the info into their device
struct. The method is called exactly once per device, during group
creation.

### HAL module integration

`iree_hal_module_create` now takes a `iree_hal_device_group_t*` instead
of `(device_count, devices[])`. The module retains the group and
delegates all device access through `iree_hal_device_group_device_count`
/ `iree_hal_device_group_device_at`. This eliminates the flexible array
member from `iree_hal_module_t`, simplifies allocation (fixed-size
struct instead of variable-size), and makes the lifetime contract
explicit: the module holds the group, the group holds the devices and
topology.

All callers are updated — CLI tooling, the high-level runtime session,
TFLite bindings, Python bindings, PJRT, ConstEval, simple_embedding
samples, check_test, and the CTS test harness.

### Testing

A mock device (`hal/testing/mock_device`) provides controllable
capabilities for testing topology construction without requiring real
hardware. The device group tests exercise builder validation (empty
builds, duplicate devices, capacity limits), single-device and
multi-device group creation, topology correctness (self-edges,
cross-device edges with expected interop modes), the convenience
function, and lifetime ordering (group outlives devices). The CTS test
harness creates a device group in `SetUpTestSuite` so every CTS test
runs with topology info assigned.

### Where this is going

The device group is the scheduling domain for the causal execution
system. When the AMDGPU driver gets its frontier-integrated semaphores
and queue operations, the device group's topology matrix is what tells
the scheduler whether a semaphore can be waited on natively or needs
handle import, whether a buffer can be read directly or needs DMA
transfer, and what the relative cost is. The group also becomes the
natural attachment point for collective channel creation and
multi-device resource pools.

---------

Co-authored-by: Claude <[email protected]>
kimm240 pushed a commit to kimm240/iree that referenced this pull request May 8, 2026
Multi-device scheduling requires knowing how devices relate to each
other: can device A wait on device B's semaphores natively, or does it
need to import a handle? Can it read B's buffers directly, or must it
issue a DMA transfer? What's the relative cost? Today the HAL has no way
to answer these questions — every cross-device interaction is handled
ad-hoc by the caller with no systematic way to discover capabilities or
make cost-based placement decisions.

This PR adds a topology matrix to the HAL that encodes directional
device relationships as packed edge descriptors. The matrix is built
once during device group creation, is immutable thereafter, and supports
lock-free concurrent queries from any thread.

### Edge design

Each edge is a 128-bit descriptor split into two 64-bit words optimized
for different access patterns:

- **Scheduling word (lo)** — read on every placement decision. Contains
interop modes (wait/signal/buffer-read/buffer-write), 16-bit capability
flags, five 4-bit cost metrics (wait, signal, copy, latency class, NUMA
distance), and a 3-bit physical link class. This is what the scheduler
reads in the nanosecond path.

- **Interop word (hi)** — read during resource import/export
negotiation. Contains four 8-bit handle type bitmasks (semaphore
import/export, buffer import/export) covering platform-specific sharing
mechanisms from POSIX fd through RDMA memory regions. This is the
microsecond path.

The split lets `iree_hal_resource_origin_t` (embedded in every semaphore
and buffer) cache only the 8-byte scheduling word for ultra-fast
compatibility checks, while the full 128-bit edge lives in the topology
matrix for the rare import/export negotiation path.

### Interop mode semantics

The 2-bit interop modes encode what the *scheduler* must do to make a
resource usable on the destination device:

- **NATIVE** — directly accessible via load/store. No action needed.
Requires `PEER_ADDRESSABLE` (mapped BARs, unified memory).
- **IMPORT** — import an external handle, then directly usable.
- **COPY** — issue a transfer command. Covers both P2P DMA (direct
device-to-device, low cost) and host-staged transfers (high cost). The
`copy_cost`, `link_class`, and `P2P_COPY` capability flag distinguish
the mechanism.
- **NONE** — not possible.

This distinction matters because P2P DMA capability (the DMA engine can
copy between devices) does not imply load/store addressability (shaders
can access remote memory). Conflating them would cause the scheduler to
reference a buffer directly in a dispatch when only DMA transfer is
available.

### Edge construction

Edges are computed in two phases: a base edge from device capabilities
(driver names, UUIDs, handle type intersections, capability flag
propagation, NUMA distance) and an optional driver-specific refinement
pass. The base computation detects same-physical-device (cross-driver
same-GPU via UUID matching), aliased devices (same-driver same-handle),
and derives interop modes from handle type intersections. Drivers can
then refine edges with hardware-specific knowledge (e.g., querying
NVLink topology, Infinity Fabric link widths).

### Platform topology queries

NUMA distance computation and CPU topology queries are factored into
platform-specific backends (sysfs on Linux, IOKit on macOS, Win32 NUMA
APIs, conservative fallback) so the core topology code stays
platform-independent.

### Where this is going

The topology matrix is the foundation for:

- **Automatic multi-device scheduling** — the scheduler uses edge costs
to decide where to place operations and how to move data between
devices, replacing today's manual device selection.
- **RDMA and distributed execution** — the handle type bitmasks and
FABRIC link class support iree/net and iree/hal/remote work for
cross-machine inference.
- **Device group creation** — the `topology` pointer in
`device_topology_info_t` will be populated by the device group, giving
every device a path to query costs against any peer.
- **Resource compatibility fast-path** — the cached scheduling word in
`resource_origin_t` enables 1-3ns "can I use this buffer/semaphore?"
checks without touching the topology matrix.

---------

Co-authored-by: Claude <[email protected]>
kimm240 pushed a commit to kimm240/iree that referenced this pull request May 8, 2026
…org#23576)

The topology matrix from iree-org#23573 needs an owner with a clear lifetime
contract. Today devices are passed to the HAL module as a flat array —
there is no object that retains the devices, owns the topology, and
guarantees the topology pointer remains valid for the duration of
execution. Every device holds a raw pointer to the topology it was
assigned, so if the topology is freed while devices are still alive,
those pointers dangle.

`iree_hal_device_group_t` is that owner. It takes already-created
devices, builds the immutable topology matrix from their capabilities,
pushes topology info into each device, and retains all of them. The
group's lifetime brackets the devices': whoever holds the devices
long-term (the HAL module, the CTS harness, a Python session) retains
the group, and the group retains the devices, so the topology pointer in
each device is guaranteed valid.

### Creation API

The builder pattern matches the topology builder it wraps:
stack-allocate, add devices, finalize. Finalize is a consuming operation
— it queries capabilities from all devices, computes edge descriptors,
calls driver-specific refinement for same-driver pairs, builds the
topology matrix, assigns topology info into each device via the new
vtable method, and produces the immutable group. The builder is zeroed
after finalize (whether it succeeds or fails) and cannot be reused.

For the common single-device case (7 of 9 callers),
`iree_hal_device_group_create_from_device` wraps the builder sequence
into a one-liner.

### `assign_topology_info` vtable method

Devices need to receive their topology info after the matrix is built —
the topology doesn't exist yet when the device is created, and the
device's index in the matrix isn't known until group creation. This is a
new vtable method on `iree_hal_device_t` that the group calls during
finalize. All existing driver implementations (local-sync, local-task,
CUDA, HIP, Vulkan, Metal, AMDGPU, null) store the info into their device
struct. The method is called exactly once per device, during group
creation.

### HAL module integration

`iree_hal_module_create` now takes a `iree_hal_device_group_t*` instead
of `(device_count, devices[])`. The module retains the group and
delegates all device access through `iree_hal_device_group_device_count`
/ `iree_hal_device_group_device_at`. This eliminates the flexible array
member from `iree_hal_module_t`, simplifies allocation (fixed-size
struct instead of variable-size), and makes the lifetime contract
explicit: the module holds the group, the group holds the devices and
topology.

All callers are updated — CLI tooling, the high-level runtime session,
TFLite bindings, Python bindings, PJRT, ConstEval, simple_embedding
samples, check_test, and the CTS test harness.

### Testing

A mock device (`hal/testing/mock_device`) provides controllable
capabilities for testing topology construction without requiring real
hardware. The device group tests exercise builder validation (empty
builds, duplicate devices, capacity limits), single-device and
multi-device group creation, topology correctness (self-edges,
cross-device edges with expected interop modes), the convenience
function, and lifetime ordering (group outlives devices). The CTS test
harness creates a device group in `SetUpTestSuite` so every CTS test
runs with topology info assigned.

### Where this is going

The device group is the scheduling domain for the causal execution
system. When the AMDGPU driver gets its frontier-integrated semaphores
and queue operations, the device group's topology matrix is what tells
the scheduler whether a semaphore can be waited on natively or needs
handle import, whether a buffer can be read directly or needs DMA
transfer, and what the relative cost is. The group also becomes the
natural attachment point for collective channel creation and
multi-device resource pools.

---------

Co-authored-by: Claude <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

hal/api IREE's public C hardware abstraction layer API

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant