Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
feat(hip): what a model engine needs from the runtime: graphs, device…
… copies, mapped memory, device queries

On #463's types: device-to-device copies and 32-bit word fills (blocking and on a stream), device addresses for
kernel arguments, pinned host memory mapped into the device, held-bytes counters with a device peak, module
globals, function attributes and occupancy, cooperative launches, device attributes and name, HIP's error names,
and graphs (stream capture, explicit kernel nodes with edges, instantiate, upload, replay, in-place node and
whole-exec updates; a refused update is HIP's verdict, not an error). Host tests run on HIP's mock; on a
W7800 (gfx1100) hip-gpu-test passes 36/36, the new tests checking every output exactly.
  • Loading branch information
BlivionIaG committed Oct 10, 2026
commit 89fd9ecae823e49120fd69aa726fef79dc1bf948
26 changes: 26 additions & 0 deletions zig/kernels/hip/runtime_tests.hip
Original file line number Diff line number Diff line change
Expand Up @@ -10,3 +10,29 @@ extern "C" __global__ void tf_hip_probe(unsigned int* out, unsigned int n,
const unsigned int i = blockIdx.x * blockDim.x + threadIdx.x;
if (i < n) out[i] = i + bias + static_cast<unsigned int>(tag >> 32);
}

__device__ int tf_hip_table[4];

extern "C" __global__ void tf_hip_fill_f32(float* out, float base, unsigned int n) {
const unsigned int i = blockIdx.x * blockDim.x + threadIdx.x;
if (i < n) out[i] = base + static_cast<float>(i);
}

extern "C" __global__ void tf_hip_axpy(float* y, const float* x, float a, unsigned int n) {
const unsigned int i = blockIdx.x * blockDim.x + threadIdx.x;
if (i < n) y[i] = a * x[i] + y[i];
}

// One thread adds to a counter, so a chain of these is a chain of dependent launches.
extern "C" __global__ void tf_hip_step(unsigned long long* counter, unsigned long long add) {
*counter += add;
}

extern "C" __global__ void tf_hip_read_table(int* out) {
out[threadIdx.x] = tf_hip_table[threadIdx.x] * 2;
}

// The wavefront width the code object runs at.
extern "C" __global__ void tf_hip_wave(int* out) {
if (threadIdx.x == 0) out[0] = warpSize;
}
96 changes: 96 additions & 0 deletions zig/src/hip/abi.zig
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,62 @@ pub const Context = ?*opaque {};
pub const Stream = ?*opaque {};
pub const Module = ?*opaque {};
pub const Function = ?*opaque {};
pub const Graph = ?*opaque {};
pub const GraphNode = ?*opaque {};
pub const GraphExec = ?*opaque {};

pub const host_malloc_portable: c_uint = 1;
pub const host_malloc_mapped: c_uint = 2;

pub const CaptureMode = enum(c_int) { global = 0, thread_local = 1, relaxed = 2 };
pub const CaptureStatus = enum(c_int) { none = 0, active = 1, invalidated = 2, _ };

/// hipDeviceAttribute_t: HIP's own numbering, not CUDA's.
pub const DeviceAttribute = enum(c_int) {
clock_rate = 5,
cooperative_launch = 10,
integrated = 16,
l2_cache_size = 19,
max_threads_per_block = 56,
multiprocessor_count = 63,
max_shared_memory_per_block = 74,
shared_mem_per_block_optin = 75,
warp_size = 87,
max_shared_memory_per_multiprocessor = 10002,
};

pub const FunctionAttribute = enum(c_int) {
max_threads_per_block = 0,
shared_size_bytes = 1,
const_size_bytes = 2,
local_size_bytes = 3,
num_regs = 4,
max_dynamic_shared_size_bytes = 8,
};

pub const Dim3 = extern struct { x: c_uint = 1, y: c_uint = 1, z: c_uint = 1 };

/// hipKernelNodeParams: its own field order (block first), 64 bytes.
pub const KernelNodeParams = extern struct {
block: Dim3,
extra: ?[*]?*anyopaque,
func: Function,
grid: Dim3,
params: ?[*]?*anyopaque,
shared_bytes: c_uint,
};

pub const ExecUpdateResult = enum(c_int) {
success = 0,
@"error" = 1,
topology_changed = 2,
node_type_changed = 3,
function_changed = 4,
parameters_changed = 5,
not_supported = 6,
unsupported_function_change = 7,
_,
};

pub const Api = struct {
hipInit: *const fn (c_uint) callconv(.c) Result,
Expand All @@ -34,6 +90,34 @@ pub const Api = struct {
hipModuleUnload: *const fn (Module) callconv(.c) Result,
hipModuleGetFunction: *const fn (*Function, Module, [*:0]const u8) callconv(.c) Result,
hipModuleLaunchKernel: *const fn (Function, c_uint, c_uint, c_uint, c_uint, c_uint, c_uint, c_uint, Stream, ?[*]?*anyopaque, ?[*]?*anyopaque) callconv(.c) Result,
hipGetErrorName: *const fn (Result) callconv(.c) ?[*:0]const u8,
hipRuntimeGetVersion: *const fn (*c_int) callconv(.c) Result,
hipDeviceGetName: *const fn ([*]u8, c_int, Device) callconv(.c) Result,
hipDeviceGetAttribute: *const fn (*c_int, DeviceAttribute, c_int) callconv(.c) Result,
hipHostGetDevicePointer: *const fn (*DevicePtr, ?*anyopaque, c_uint) callconv(.c) Result,
hipMemcpyDtoD: *const fn (DevicePtr, DevicePtr, usize) callconv(.c) Result,
hipMemcpyDtoDAsync: *const fn (DevicePtr, DevicePtr, usize, Stream) callconv(.c) Result,
hipMemsetD32: *const fn (DevicePtr, c_int, usize) callconv(.c) Result,
hipMemsetD32Async: *const fn (DevicePtr, c_int, usize, Stream) callconv(.c) Result,
hipModuleGetGlobal: *const fn (*DevicePtr, *usize, Module, [*:0]const u8) callconv(.c) Result,
hipFuncGetAttribute: *const fn (*c_int, FunctionAttribute, Function) callconv(.c) Result,
hipModuleOccupancyMaxActiveBlocksPerMultiprocessor: *const fn (*c_int, Function, c_int, usize) callconv(.c) Result,
hipModuleLaunchCooperativeKernel: *const fn (Function, c_uint, c_uint, c_uint, c_uint, c_uint, c_uint, c_uint, Stream, ?[*]?*anyopaque) callconv(.c) Result,
hipStreamBeginCapture: *const fn (Stream, CaptureMode) callconv(.c) Result,
hipStreamEndCapture: *const fn (Stream, *Graph) callconv(.c) Result,
hipStreamIsCapturing: *const fn (Stream, *CaptureStatus) callconv(.c) Result,
hipGraphCreate: *const fn (*Graph, c_uint) callconv(.c) Result,
hipGraphDestroy: *const fn (Graph) callconv(.c) Result,
hipGraphAddKernelNode: *const fn (*GraphNode, Graph, ?[*]const GraphNode, usize, *const KernelNodeParams) callconv(.c) Result,
hipGraphKernelNodeSetParams: *const fn (GraphNode, *const KernelNodeParams) callconv(.c) Result,
hipGraphAddDependencies: *const fn (Graph, [*]const GraphNode, [*]const GraphNode, usize) callconv(.c) Result,
hipGraphGetNodes: *const fn (Graph, ?[*]GraphNode, *usize) callconv(.c) Result,
hipGraphInstantiateWithFlags: *const fn (*GraphExec, Graph, c_ulonglong) callconv(.c) Result,
hipGraphUpload: *const fn (GraphExec, Stream) callconv(.c) Result,
hipGraphLaunch: *const fn (GraphExec, Stream) callconv(.c) Result,
hipGraphExecDestroy: *const fn (GraphExec) callconv(.c) Result,
hipGraphExecUpdate: *const fn (GraphExec, Graph, *GraphNode, *ExecUpdateResult) callconv(.c) Result,
hipGraphExecKernelNodeSetParams: *const fn (GraphExec, GraphNode, *const KernelNodeParams) callconv(.c) Result,
};

test "HIP ABI handles and scalar types have C widths" {
Expand All @@ -43,4 +127,16 @@ test "HIP ABI handles and scalar types have C widths" {
try std.testing.expectEqual(@sizeOf(*anyopaque), @sizeOf(Stream));
try std.testing.expectEqual(@sizeOf(*anyopaque), @sizeOf(Module));
try std.testing.expectEqual(@sizeOf(*anyopaque), @sizeOf(Function));
try std.testing.expectEqual(@sizeOf(*anyopaque), @sizeOf(Graph));
try std.testing.expectEqual(@sizeOf(c_int), @sizeOf(DeviceAttribute));
}

test "hipKernelNodeParams keeps HIP's layout" {
try std.testing.expectEqual(64, @sizeOf(KernelNodeParams));
try std.testing.expectEqual(0, @offsetOf(KernelNodeParams, "block"));
try std.testing.expectEqual(16, @offsetOf(KernelNodeParams, "extra"));
try std.testing.expectEqual(24, @offsetOf(KernelNodeParams, "func"));
try std.testing.expectEqual(32, @offsetOf(KernelNodeParams, "grid"));
try std.testing.expectEqual(48, @offsetOf(KernelNodeParams, "params"));
try std.testing.expectEqual(56, @offsetOf(KernelNodeParams, "shared_bytes"));
}
1 change: 1 addition & 0 deletions zig/src/hip/admission_tests.zig
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ test {
_ = @import("abi.zig");
_ = @import("runtime.zig");
_ = @import("launch.zig");
_ = @import("graph.zig");
_ = @import("context.zig").Context.init;
_ = @import("stream.zig").Stream.init;
_ = @import("memory.zig").DeviceBuffer.alloc;
Expand Down
13 changes: 13 additions & 0 deletions zig/src/hip/context.zig
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,19 @@ pub const Context = struct {
try runtime.check(self.r.api.hipDeviceSynchronize());
}

pub fn attribute(self: Context, a: abi.DeviceAttribute) runtime.Error!c_int {
var v: c_int = 0;
try runtime.check(self.r.api.hipDeviceGetAttribute(&v, a, self.device));
return v;
}

/// The device's marketing name ("AMD Radeon PRO W7800" ...).
pub fn name(self: Context, buf: []u8) runtime.Error![]const u8 {
if (buf.len < 2) return error.Invalid;
try runtime.check(self.r.api.hipDeviceGetName(buf.ptr, @intCast(buf.len), self.device));
return std.mem.sliceTo(buf, 0);
}

pub fn deinit(self: *Context) void {
_ = self.r.api.hipDeviceSynchronize();
_ = self.r.api.hipDevicePrimaryCtxRelease(self.device);
Expand Down
166 changes: 166 additions & 0 deletions zig/src/hip/graph.zig
Original file line number Diff line number Diff line change
@@ -0,0 +1,166 @@
//! HIP graphs: captured from a stream or built node by node, instantiated once, replayed and updated in place.
const abi = @import("abi.zig");
const runtime = @import("runtime.zig");
const std = @import("std");
const Stream = @import("stream.zig").Stream;
const Function = @import("module.zig").Function;
const launch = @import("launch.zig");

pub const Node = abi.GraphNode;

/// Every launch on `stream` is recorded until `endCapture`; nothing runs.
pub fn beginCapture(stream: Stream, mode: abi.CaptureMode) runtime.Error!void {
try runtime.check(stream.r.api.hipStreamBeginCapture(stream.handle, mode));
}

/// An invalidated capture returns an error and no graph.
pub fn endCapture(stream: Stream) runtime.Error!Graph {
var g: abi.Graph = null;
try runtime.check(stream.r.api.hipStreamEndCapture(stream.handle, &g));
if (g == null) return error.Invalid;
return .{ .r = stream.r, .handle = g };
}

pub fn captureStatus(stream: Stream) runtime.Error!abi.CaptureStatus {
var s: abi.CaptureStatus = .none;
try runtime.check(stream.r.api.hipStreamIsCapturing(stream.handle, &s));
return s;
}

/// A cooperative launch has no graph node form.
fn nodeParams(r: *const runtime.Runtime, f: Function, cfg: launch.Config, args: *launch.Args) runtime.Error!abi.KernelNodeParams {
try cfg.validate();
if (cfg.cooperative or f.r != r) return error.Invalid;
return .{
.block = .{ .x = cfg.block.x, .y = cfg.block.y, .z = cfg.block.z },
.extra = null,
.func = f.handle,
.grid = .{ .x = cfg.grid.x, .y = cfg.grid.y, .z = cfg.grid.z },
.params = args.pointers(),
.shared_bytes = cfg.shared,
};
}

pub const Graph = struct {
r: *const runtime.Runtime,
handle: abi.Graph,

pub fn init(r: *const runtime.Runtime) runtime.Error!Graph {
var g: abi.Graph = null;
try runtime.check(r.api.hipGraphCreate(&g, 0));
if (g == null) return error.Invalid;
return .{ .r = r, .handle = g };
}

pub fn deinit(self: *Graph) void {
_ = self.r.api.hipGraphDestroy(self.handle);
self.* = undefined;
}

/// A kernel node after `deps`; HIP copies the argument values, so `args` may change afterwards.
pub fn addKernel(self: Graph, deps: []const Node, f: Function, cfg: launch.Config, args: *launch.Args) runtime.Error!Node {
const p = try nodeParams(self.r, f, cfg, args);
var n: Node = null;
try runtime.check(self.r.api.hipGraphAddKernelNode(&n, self.handle, if (deps.len > 0) deps.ptr else null, deps.len, &p));
return n;
}

/// New arguments or geometry for a node of this graph, before it is instantiated or an exec is updated from it.
pub fn setKernel(self: Graph, node: Node, f: Function, cfg: launch.Config, args: *launch.Args) runtime.Error!void {
const p = try nodeParams(self.r, f, cfg, args);
try runtime.check(self.r.api.hipGraphKernelNodeSetParams(node, &p));
}

pub fn depend(self: Graph, from: Node, to: Node) runtime.Error!void {
const a = [1]Node{from};
const b = [1]Node{to};
try runtime.check(self.r.api.hipGraphAddDependencies(self.handle, &a, &b, 1));
}

/// Fills `out` with the graph's nodes (capture order for a captured graph) and returns them.
pub fn nodes(self: Graph, out: []Node) runtime.Error![]Node {
var n: usize = out.len;
try runtime.check(self.r.api.hipGraphGetNodes(self.handle, out.ptr, &n));
if (n > out.len) return error.Invalid;
return out[0..n];
}

pub fn instantiate(self: Graph) runtime.Error!Exec {
var e: abi.GraphExec = null;
try runtime.check(self.r.api.hipGraphInstantiateWithFlags(&e, self.handle, 0));
if (e == null) return error.Invalid;
return .{ .r = self.r, .handle = e };
}
};

pub const Exec = struct {
r: *const runtime.Runtime,
handle: abi.GraphExec,

pub fn deinit(self: *Exec) void {
_ = self.r.api.hipGraphExecDestroy(self.handle);
self.* = undefined;
}

/// Moves the graph's work to the device ahead of the first launch, so that launch pays no setup.
pub fn upload(self: Exec, stream: Stream) runtime.Error!void {
if (self.r != stream.r) return error.Invalid;
try runtime.check(self.r.api.hipGraphUpload(self.handle, stream.handle));
}

pub fn launchOn(self: Exec, stream: Stream) runtime.Error!void {
if (self.r != stream.r) return error.Invalid;
try runtime.check(self.r.api.hipGraphLaunch(self.handle, stream.handle));
}

/// One kernel node's arguments or geometry, changed in the executable graph without rebuilding it.
pub fn setKernel(self: Exec, node: Node, f: Function, cfg: launch.Config, args: *launch.Args) runtime.Error!void {
const p = try nodeParams(self.r, f, cfg, args);
try runtime.check(self.r.api.hipGraphExecKernelNodeSetParams(self.handle, node, &p));
}

/// Every node's parameters from `g`, which must keep the topology; a refused update leaves the exec unchanged.
pub fn update(self: Exec, g: Graph) runtime.Error!abi.ExecUpdateResult {
var node: Node = null;
var result: abi.ExecUpdateResult = .success;
const res = self.r.api.hipGraphExecUpdate(self.handle, g.handle, &node, &result);
if (result != .success) return result;
try runtime.check(res);
return .success;
}
};

test "kernel nodes refuse cooperative launches, bad geometry and foreign functions before HIP" {
var r: runtime.Runtime = undefined;
var other: runtime.Runtime = undefined;
var args: launch.Args = .{};
const f: Function = .{ .r = &r, .handle = @ptrFromInt(64) };
const ok: launch.Config = .{ .grid = .{ .x = 2 }, .block = .{ .x = 64, .y = 2 }, .shared = 128 };
const p = try nodeParams(&r, f, ok, &args);
try std.testing.expectEqual(@as(c_uint, 2), p.grid.x);
try std.testing.expectEqual(@as(c_uint, 2), p.block.y);
try std.testing.expectEqual(@as(c_uint, 128), p.shared_bytes);
try std.testing.expectError(error.Invalid, nodeParams(&r, f, .{ .grid = .{ .x = 1 }, .block = .{ .x = 64 }, .cooperative = true }, &args));
try std.testing.expectError(error.Invalid, nodeParams(&r, f, .{ .grid = .{ .x = 1 }, .block = .{ .x = 2048 } }, &args));
try std.testing.expectError(error.Invalid, nodeParams(&other, f, ok, &args));
}

test "a refused exec update reports HIP's verdict, not an error" {
const Mock = struct {
fn refuse(_: abi.GraphExec, _: abi.Graph, node: *abi.GraphNode, result: *abi.ExecUpdateResult) callconv(.c) abi.Result {
node.* = null;
result.* = .topology_changed;
return 1;
}
fn fail(_: abi.GraphExec, _: abi.Graph, _: *abi.GraphNode, _: *abi.ExecUpdateResult) callconv(.c) abi.Result {
return 1;
}
};
var r: runtime.Runtime = undefined;
r.api.hipGraphExecUpdate = Mock.refuse;
const e: Exec = .{ .r = &r, .handle = @ptrFromInt(8) };
const g: Graph = .{ .r = &r, .handle = @ptrFromInt(16) };
try std.testing.expectEqual(abi.ExecUpdateResult.topology_changed, try e.update(g));
r.api.hipGraphExecUpdate = Mock.fail;
try std.testing.expectError(error.HipFailed, e.update(g));
}
33 changes: 32 additions & 1 deletion zig/src/hip/launch.zig
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
//! Plain HIP module launches; no CUDA cluster or programmatic-launch attributes.
const std = @import("std");
const abi = @import("abi.zig");
const runtime = @import("runtime.zig");
const Function = @import("module.zig").Function;
const Stream = @import("stream.zig").Stream;
Expand All @@ -9,6 +10,8 @@ pub const Config = struct {
grid: Dim3,
block: Dim3,
shared: u32 = 0,
/// hipModuleLaunchCooperativeKernel: every block resident at once, so blocks may wait on each other.
cooperative: bool = false,

pub fn validate(self: Config) runtime.Error!void {
const g = self.grid;
Expand All @@ -28,7 +31,11 @@ pub fn launch(f: Function, cfg: Config, stream: Stream, args: *Args) runtime.Err
if (f.r != stream.r) return error.Invalid;
const g = cfg.grid;
const b = cfg.block;
try runtime.check(f.r.api.hipModuleLaunchKernel(f.handle, g.x, g.y, g.z, b.x, b.y, b.z, cfg.shared, stream.handle, args.pointers(), null));
if (cfg.cooperative) {
try runtime.check(f.r.api.hipModuleLaunchCooperativeKernel(f.handle, g.x, g.y, g.z, b.x, b.y, b.z, cfg.shared, stream.handle, args.pointers()));
} else {
try runtime.check(f.r.api.hipModuleLaunchKernel(f.handle, g.x, g.y, g.z, b.x, b.y, b.z, cfg.shared, stream.handle, args.pointers(), null));
}
}

test "launch geometry refuses zero, oversized blocks and dimension overflow" {
Expand All @@ -37,3 +44,27 @@ test "launch geometry refuses zero, oversized blocks and dimension overflow" {
try std.testing.expectError(error.Invalid, (Config{ .grid = .{ .x = 1 }, .block = .{ .x = 1024, .y = 2 } }).validate());
try std.testing.expectError(error.Invalid, (Config{ .grid = .{ .x = std.math.maxInt(u32) }, .block = .{ .x = 2 } }).validate());
}

test "a cooperative launch takes HIP's cooperative entry point" {
const Mock = struct {
var which: u8 = 0;
fn plain(_: abi.Function, _: c_uint, _: c_uint, _: c_uint, _: c_uint, _: c_uint, _: c_uint, _: c_uint, _: abi.Stream, _: ?[*]?*anyopaque, _: ?[*]?*anyopaque) callconv(.c) abi.Result {
which = 'p';
return 0;
}
fn coop(_: abi.Function, _: c_uint, _: c_uint, _: c_uint, _: c_uint, _: c_uint, _: c_uint, _: c_uint, _: abi.Stream, _: ?[*]?*anyopaque) callconv(.c) abi.Result {
which = 'c';
return 0;
}
};
var r: runtime.Runtime = undefined;
r.api.hipModuleLaunchKernel = Mock.plain;
r.api.hipModuleLaunchCooperativeKernel = Mock.coop;
const f: Function = .{ .r = &r, .handle = @ptrFromInt(64) };
const s: Stream = .{ .r = &r, .handle = @ptrFromInt(32) };
var args: Args = .{};
try launch(f, .{ .grid = .{ .x = 1 }, .block = .{ .x = 32 } }, s, &args);
try std.testing.expectEqual(@as(u8, 'p'), Mock.which);
try launch(f, .{ .grid = .{ .x = 1 }, .block = .{ .x = 32 }, .cooperative = true }, s, &args);
try std.testing.expectEqual(@as(u8, 'c'), Mock.which);
}
Loading