From b69f009d16b43a74e33527ebc44c50eef85a3be5 Mon Sep 17 00:00:00 2001 From: BlivionIaG <15323295+BlivionIaG@users.noreply.github.com> Date: Sat, 10 Oct 2026 12:35:51 +0200 Subject: [PATCH 1/3] build(hip): -Dhip-arch accepts gfx1030 (RDNA2) and gfx1100 (RDNA3) The runtime and the affine row kernel need no change: the reduction is 32 lanes wide on any wave size, and the loader takes only the device's exact object. On a Radeon PRO W7800 (gfx1100), hip-gpu-test passes 16/16 and hip-affine-test 22/22; a gfx1151 object on it is refused with UnsupportedArchitecture. --- zig/build/hip.zig | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/zig/build/hip.zig b/zig/build/hip.zig index 26c24fb646b..041f40f534f 100644 --- a/zig/build/hip.zig +++ b/zig/build/hip.zig @@ -29,8 +29,9 @@ pub fn steps(b: *std.Build, target: std.Build.ResolvedTarget, test_step: *std.Bu const hip_include = b.option([]const u8, "hip-include", "HIP header directory") orelse b.pathResolve(&.{ std.fs.path.dirname(hipcc_resolved) orelse "/opt/rocm/bin", "..", "include" }); const hip_arch = b.option([]const u8, "hip-arch", "Exact GPU architecture for the probe code object") orelse "gfx1151"; - if (!std.mem.eql(u8, hip_arch, "gfx1150") and !std.mem.eql(u8, hip_arch, "gfx1151") and !std.mem.eql(u8, hip_arch, "gfx1201")) - @panic("unsupported HIP probe architecture"); + for ([_][]const u8{ "gfx1030", "gfx1100", "gfx1150", "gfx1151", "gfx1201" }) |supported| { + if (std.mem.eql(u8, hip_arch, supported)) break; + } else @panic("unsupported HIP probe architecture"); const hip_compile = b.addSystemCommand(&.{ hipcc, "--genco", b.fmt("--offload-arch={s}", .{hip_arch}), "-O2", "-ffp-contract=off" }); hip_compile.addFileArg(b.path("zig/kernels/hip/runtime_tests.hip")); hip_compile.addArg("-o"); From 5d2bb92aaeaec134b026c35489460812886dfc8f Mon Sep 17 00:00:00 2001 From: BlivionIaG <15323295+BlivionIaG@users.noreply.github.com> Date: Sat, 10 Oct 2026 12:38:21 +0200 Subject: [PATCH 2/3] feat(hip): a caps table from RDNA2 to RDNA4, keyed by exact gfx name Each generation's row lists its parts and the instructions kernels test (dot2 f16/bf16, sdot4/8, the WMMA layout, the activation type); kernels will read these, never the GPU's name. -Dhip-arch now takes any exact name in the table, and the GPU test checks the device's own name is in it. On a W7800 (gfx1100): hip-gpu-test 19/19, hip-affine-test 22/22 with its bits unchanged. --- zig/build/hip.zig | 6 +-- zig/src/hip/admission_tests.zig | 1 + zig/src/hip/caps.zig | 68 +++++++++++++++++++++++++++++++++ zig/src/hip/runtime_tests.zig | 1 + 4 files changed, 73 insertions(+), 3 deletions(-) create mode 100644 zig/src/hip/caps.zig diff --git a/zig/build/hip.zig b/zig/build/hip.zig index 041f40f534f..64f05a07863 100644 --- a/zig/build/hip.zig +++ b/zig/build/hip.zig @@ -1,6 +1,7 @@ //! HIP: mock-backed admission tests join `zig build test`; GPU builds and runs are opt-in steps (-Dhipcc, -Dhip-include, -Dhip-arch). const std = @import("std"); +const caps = @import("../src/hip/caps.zig"); /// hip-host-test (part of `test`), hip-gpu-build and hip-gpu-test, hip-affine-build and hip-affine-test. pub fn steps(b: *std.Build, target: std.Build.ResolvedTarget, test_step: *std.Build.Step) void { @@ -29,9 +30,8 @@ pub fn steps(b: *std.Build, target: std.Build.ResolvedTarget, test_step: *std.Bu const hip_include = b.option([]const u8, "hip-include", "HIP header directory") orelse b.pathResolve(&.{ std.fs.path.dirname(hipcc_resolved) orelse "/opt/rocm/bin", "..", "include" }); const hip_arch = b.option([]const u8, "hip-arch", "Exact GPU architecture for the probe code object") orelse "gfx1151"; - for ([_][]const u8{ "gfx1030", "gfx1100", "gfx1150", "gfx1151", "gfx1201" }) |supported| { - if (std.mem.eql(u8, hip_arch, supported)) break; - } else @panic("unsupported HIP probe architecture"); + if (caps.Caps.of(hip_arch) == null or std.mem.indexOfScalar(u8, hip_arch, ':') != null) + std.debug.panic("-Dhip-arch {s} is not an exact name in the caps table (zig/src/hip/caps.zig)", .{hip_arch}); const hip_compile = b.addSystemCommand(&.{ hipcc, "--genco", b.fmt("--offload-arch={s}", .{hip_arch}), "-O2", "-ffp-contract=off" }); hip_compile.addFileArg(b.path("zig/kernels/hip/runtime_tests.hip")); hip_compile.addArg("-o"); diff --git a/zig/src/hip/admission_tests.zig b/zig/src/hip/admission_tests.zig index a1b9c840668..d9d854ee182 100644 --- a/zig/src/hip/admission_tests.zig +++ b/zig/src/hip/admission_tests.zig @@ -5,6 +5,7 @@ const fixtures = @import("hip_fixtures"); test { _ = @import("affine.zig"); _ = @import("args.zig"); + _ = @import("caps.zig"); _ = @import("code_object.zig"); _ = @import("abi.zig"); _ = @import("runtime.zig"); diff --git a/zig/src/hip/caps.zig b/zig/src/hip/caps.zig new file mode 100644 index 00000000000..8ee61f99f23 --- /dev/null +++ b/zig/src/hip/caps.zig @@ -0,0 +1,68 @@ +//! What an RDNA GPU can do, from its exact gfx name; kernels test these capabilities, never the name. +const std = @import("std"); + +pub const Matrix = enum { none, wmma11, wmma12 }; +pub const Act = enum { f16, bf16 }; +pub const Generation = enum { rdna2, rdna3, rdna3_5, rdna4 }; + +pub const Caps = struct { + wave: u8, + dot2_f16: bool, + dot2_bf16: bool, + sdot4: bool, + sdot8: bool, + matrix: Matrix, + act: Act, + generation: Generation, + + /// The caps of `name` ("gfx1030", "gfx1151:xnack-" ...), or null for a GPU outside the table. + pub fn of(name: []const u8) ?Caps { + const end = std.mem.indexOfScalar(u8, name, ':') orelse name.len; + for (table) |row| { + for (row.names) |n| if (std.mem.eql(u8, n, name[0..end])) return row.caps; + } + return null; + } + + /// The gfx names of `generation`, in table order. + pub fn names(generation: Generation) []const []const u8 { + for (table) |row| if (row.caps.generation == generation) return row.names; + unreachable; + } +}; + +const Row = struct { names: []const []const u8, caps: Caps }; + +/// One row a generation; every part of it shares the instructions the kernels use. +const table = [_]Row{ + .{ .names = &.{ "gfx1030", "gfx1031", "gfx1032", "gfx1033", "gfx1034", "gfx1035", "gfx1036" }, .caps = .{ .wave = 32, .dot2_f16 = true, .dot2_bf16 = false, .sdot4 = true, .sdot8 = true, .matrix = .none, .act = .f16, .generation = .rdna2 } }, + .{ .names = &.{ "gfx1100", "gfx1101", "gfx1102", "gfx1103" }, .caps = .{ .wave = 32, .dot2_f16 = true, .dot2_bf16 = true, .sdot4 = true, .sdot8 = true, .matrix = .wmma11, .act = .bf16, .generation = .rdna3 } }, + .{ .names = &.{ "gfx1150", "gfx1151", "gfx1152", "gfx1153" }, .caps = .{ .wave = 32, .dot2_f16 = true, .dot2_bf16 = true, .sdot4 = true, .sdot8 = true, .matrix = .wmma11, .act = .bf16, .generation = .rdna3_5 } }, + .{ .names = &.{ "gfx1200", "gfx1201" }, .caps = .{ .wave = 32, .dot2_f16 = true, .dot2_bf16 = true, .sdot4 = true, .sdot8 = true, .matrix = .wmma12, .act = .bf16, .generation = .rdna4 } }, +}; + +test "each generation gets its instructions" { + const rdna2 = Caps.of("gfx1030").?; + try std.testing.expect(rdna2.dot2_f16 and !rdna2.dot2_bf16 and rdna2.matrix == .none and rdna2.act == .f16); + const rdna3 = Caps.of("gfx1100").?; + try std.testing.expect(rdna3.dot2_bf16 and rdna3.matrix == .wmma11 and rdna3.act == .bf16); + try std.testing.expectEqual(Generation.rdna3_5, Caps.of("gfx1151:xnack-").?.generation); + try std.testing.expectEqual(Matrix.wmma12, Caps.of("gfx1201").?.matrix); + for (table) |row| try std.testing.expectEqual(@as(u8, 32), row.caps.wave); +} + +test "names outside the table are refused" { + for ([_][]const u8{ "gfx1010", "gfx1037", "gfx1104", "gfx1202", "gfx906", "gfx90a", "gfx", "", "sm_90", "gfx11000" }) |name| + try std.testing.expect(Caps.of(name) == null); +} + +test "every name is in exactly one generation" { + var count: usize = 0; + for (std.enums.values(Generation)) |g| { + for (Caps.names(g)) |n| { + try std.testing.expectEqual(g, Caps.of(n).?.generation); + count += 1; + } + } + try std.testing.expectEqual(@as(usize, 17), count); +} diff --git a/zig/src/hip/runtime_tests.zig b/zig/src/hip/runtime_tests.zig index 71b482899d5..7d0bdececc3 100644 --- a/zig/src/hip/runtime_tests.zig +++ b/zig/src/hip/runtime_tests.zig @@ -42,6 +42,7 @@ test "HIP copies fills and mixed-width kernel arguments on real GPU" { try std.testing.expectError(error.Invalid, b.upload(b.len, &.{1})); var arch_buffer: [256]u8 = undefined; const arch = try @import("device_arch.zig").query(&r, 0, &arch_buffer); + try std.testing.expect(@import("caps.zig").Caps.of(arch) != null); const images = [_]@import("code_object.zig").Image{.{ .arch = codeobject.arch, .bytes = &codeobject.bytes }}; try std.testing.expectError(error.UnsupportedArchitecture, Module.loadForArchitecture(&r, &images, "gfx9999")); var m = try Module.loadForArchitecture(&r, &images, arch); From 89fd9ecae823e49120fd69aa726fef79dc1bf948 Mon Sep 17 00:00:00 2001 From: BlivionIaG <15323295+BlivionIaG@users.noreply.github.com> Date: Sat, 10 Oct 2026 12:44:18 +0200 Subject: [PATCH 3/3] 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. --- zig/kernels/hip/runtime_tests.hip | 26 ++++ zig/src/hip/abi.zig | 96 +++++++++++++ zig/src/hip/admission_tests.zig | 1 + zig/src/hip/context.zig | 13 ++ zig/src/hip/graph.zig | 166 ++++++++++++++++++++++ zig/src/hip/launch.zig | 33 ++++- zig/src/hip/memory.zig | 169 +++++++++++++++++++++- zig/src/hip/module.zig | 29 +++- zig/src/hip/runtime.zig | 6 + zig/src/hip/runtime_tests.zig | 223 ++++++++++++++++++++++++++++++ 10 files changed, 759 insertions(+), 3 deletions(-) create mode 100644 zig/src/hip/graph.zig diff --git a/zig/kernels/hip/runtime_tests.hip b/zig/kernels/hip/runtime_tests.hip index 8a4ca2cdf51..82606940914 100644 --- a/zig/kernels/hip/runtime_tests.hip +++ b/zig/kernels/hip/runtime_tests.hip @@ -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(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(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; +} diff --git a/zig/src/hip/abi.zig b/zig/src/hip/abi.zig index 8e269166011..ed23c1416b8 100644 --- a/zig/src/hip/abi.zig +++ b/zig/src/hip/abi.zig @@ -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, @@ -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" { @@ -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")); } diff --git a/zig/src/hip/admission_tests.zig b/zig/src/hip/admission_tests.zig index d9d854ee182..9d55184ec7e 100644 --- a/zig/src/hip/admission_tests.zig +++ b/zig/src/hip/admission_tests.zig @@ -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; diff --git a/zig/src/hip/context.zig b/zig/src/hip/context.zig index adeb98c2101..e5cea37b5dc 100644 --- a/zig/src/hip/context.zig +++ b/zig/src/hip/context.zig @@ -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); diff --git a/zig/src/hip/graph.zig b/zig/src/hip/graph.zig new file mode 100644 index 00000000000..ab79cf42b4a --- /dev/null +++ b/zig/src/hip/graph.zig @@ -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)); +} diff --git a/zig/src/hip/launch.zig b/zig/src/hip/launch.zig index 23c97132f80..2b8a5133cb3 100644 --- a/zig/src/hip/launch.zig +++ b/zig/src/hip/launch.zig @@ -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; @@ -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; @@ -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" { @@ -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); +} diff --git a/zig/src/hip/memory.zig b/zig/src/hip/memory.zig index 5abf94f6801..9c3dd094f41 100644 --- a/zig/src/hip/memory.zig +++ b/zig/src/hip/memory.zig @@ -3,6 +3,35 @@ const abi = @import("abi.zig"); const runtime = @import("runtime.zig"); const std = @import("std"); +/// Bytes this process holds in DeviceBuffers and HostBuffers, and the device peak since the last reset. +pub const Usage = struct { device: u64, host: u64, peak: u64 }; + +var counts_lock: std.atomic.Mutex = .unlocked; +var device_bytes: u64 = 0; +var host_bytes: u64 = 0; +var peak_bytes: u64 = 0; + +/// The counts now; `reset_peak` starts a new peak at the current device bytes. Safe from any thread. +pub fn usage(reset_peak: bool) Usage { + lock(); + defer counts_lock.unlock(); + if (reset_peak) peak_bytes = device_bytes; + return .{ .device = device_bytes, .host = host_bytes, .peak = peak_bytes }; +} + +fn count(device: bool, held: usize, freed: usize) void { + lock(); + defer counts_lock.unlock(); + if (device) { + device_bytes = device_bytes + held - freed; + peak_bytes = @max(peak_bytes, device_bytes); + } else host_bytes = host_bytes + held - freed; +} + +fn lock() void { + while (!counts_lock.tryLock()) std.Thread.yield() catch {}; +} + pub const DeviceBuffer = struct { r: *const runtime.Runtime, ptr: abi.DevicePtr, @@ -14,14 +43,30 @@ pub const DeviceBuffer = struct { try runtime.check(r.api.hipMalloc(&ptr, len)); if (ptr == null) return error.Invalid; } + count(true, len, 0); return .{ .r = r, .ptr = ptr, .len = len }; } + /// Allocates and fills from host bytes in one call. + pub fn fromHost(r: *const runtime.Runtime, bytes: []const u8) runtime.Error!DeviceBuffer { + var b = try alloc(r, bytes.len); + errdefer b.free(); + try b.upload(0, bytes); + return b; + } + pub fn free(self: *DeviceBuffer) void { if (self.ptr != null) _ = self.r.api.hipFree(self.ptr); + count(true, 0, self.len); self.* = undefined; } + /// The device address `offset` bytes in, as kernel arguments and device copies take it; past the end is refused. + pub fn address(self: DeviceBuffer, offset: usize) runtime.Error!u64 { + if (offset > self.len) return error.Invalid; + return @intFromPtr(self.ptr) + offset; + } + fn span(self: DeviceBuffer, offset: usize, len: usize) runtime.Error!abi.DevicePtr { if (offset > self.len or len > self.len - offset) return error.Invalid; if (self.ptr) |p| return @ptrFromInt(@intFromPtr(p) + offset); @@ -64,6 +109,35 @@ pub const DeviceBuffer = struct { const src = try self.span(offset, host.bytes.len); if (host.bytes.len != 0) try runtime.check(self.r.api.hipMemcpyDtoHAsync(host.bytes.ptr, src, host.bytes.len, stream.handle)); } + + /// Blocks until the device-to-device copy from `src` (a device address) completes. + pub fn copyFrom(self: DeviceBuffer, offset: usize, src: u64, n: usize) runtime.Error!void { + const dst = try self.span(offset, n); + if (n == 0) return; + try runtime.check(self.r.api.hipMemcpyDtoD(dst, @ptrFromInt(src), n)); + try runtime.check(self.r.api.hipStreamSynchronize(null)); + } + + /// `src` must stay allocated until the stream completes. + pub fn copyFromAsync(self: DeviceBuffer, offset: usize, src: u64, n: usize, stream: @import("stream.zig").Stream) runtime.Error!void { + if (self.r != stream.r) return error.Invalid; + const dst = try self.span(offset, n); + if (n != 0) try runtime.check(self.r.api.hipMemcpyDtoDAsync(dst, @ptrFromInt(src), n, stream.handle)); + } + + /// Fills whole 32-bit words and blocks until done; the length must be a multiple of four. + pub fn fill32(self: DeviceBuffer, value: u32) runtime.Error!void { + if (self.len % 4 != 0) return error.Invalid; + if (self.len != 0) { + try runtime.check(self.r.api.hipMemsetD32(self.ptr, @bitCast(value), self.len / 4)); + try runtime.check(self.r.api.hipStreamSynchronize(null)); + } + } + + pub fn fill32Async(self: DeviceBuffer, value: u32, stream: @import("stream.zig").Stream) runtime.Error!void { + if (self.r != stream.r or self.len % 4 != 0) return error.Invalid; + if (self.len != 0) try runtime.check(self.r.api.hipMemsetD32Async(self.ptr, @bitCast(value), self.len / 4, stream.handle)); + } }; pub const HostBuffer = struct { @@ -71,17 +145,36 @@ pub const HostBuffer = struct { bytes: []u8, pub fn alloc(r: *const runtime.Runtime, len: usize) runtime.Error!HostBuffer { + return allocFlags(r, len, 0); + } + + /// Pinned bytes mapped into the device's address space: kernels read and write them with no copy. + pub fn allocMapped(r: *const runtime.Runtime, len: usize) runtime.Error!HostBuffer { + return allocFlags(r, len, abi.host_malloc_portable | abi.host_malloc_mapped); + } + + fn allocFlags(r: *const runtime.Runtime, len: usize, flags: c_uint) runtime.Error!HostBuffer { if (len == 0) return error.Invalid; var ptr: abi.DevicePtr = null; - try runtime.check(r.api.hipHostMalloc(&ptr, len, 0)); + try runtime.check(r.api.hipHostMalloc(&ptr, len, flags)); if (ptr == null) return error.Invalid; const bytes: [*]u8 = @ptrCast(ptr.?); + count(false, len, 0); return .{ .r = r, .bytes = bytes[0..len] }; } + /// The device address of a mapped buffer. + pub fn device(self: HostBuffer) runtime.Error!u64 { + var ptr: abi.DevicePtr = null; + try runtime.check(self.r.api.hipHostGetDevicePointer(&ptr, self.bytes.ptr, 0)); + if (ptr == null) return error.Invalid; + return @intFromPtr(ptr); + } + /// All streams using these bytes must have completed before release. pub fn free(self: *HostBuffer) void { _ = self.r.api.hipHostFree(self.bytes.ptr); + count(false, 0, self.bytes.len); self.* = undefined; } }; @@ -160,3 +253,77 @@ test "async copies reject foreign owners and out-of-range bytes before HIP" { try std.testing.expectError(error.Invalid, b.uploadAsync(1, host, stream)); try std.testing.expectError(error.Invalid, b.downloadAsync(1, host, stream)); } + +test "word fills refuse partial words and synchronize only the blocking path" { + const Mock = struct { + var calls: u32 = 0; + var words: usize = 0; + fn fill(_: abi.DevicePtr, value: c_int, n: usize) callconv(.c) abi.Result { + calls = calls * 10 + 1; + words = n; + return if (value == -559038737) 0 else 1; + } + fn asyncFill(_: abi.DevicePtr, _: c_int, n: usize, _: abi.Stream) callconv(.c) abi.Result { + calls = calls * 10 + 3; + words = n; + return 0; + } + fn sync(_: abi.Stream) callconv(.c) abi.Result { + calls = calls * 10 + 2; + return 0; + } + }; + var r: runtime.Runtime = undefined; + r.api.hipMemsetD32 = Mock.fill; + r.api.hipMemsetD32Async = Mock.asyncFill; + r.api.hipStreamSynchronize = Mock.sync; + const b: DeviceBuffer = .{ .r = &r, .ptr = @ptrFromInt(16), .len = 32 }; + try b.fill32(0xdeadbeef); + try std.testing.expectEqual(@as(u32, 12), Mock.calls); + try std.testing.expectEqual(@as(usize, 8), Mock.words); + Mock.calls = 0; + try b.fill32Async(0, .{ .r = &r, .handle = @ptrFromInt(32) }); + try std.testing.expectEqual(@as(u32, 3), Mock.calls); + Mock.calls = 0; + const odd: DeviceBuffer = .{ .r = &r, .ptr = @ptrFromInt(16), .len = 30 }; + try std.testing.expectError(error.Invalid, odd.fill32(0)); + try std.testing.expectError(error.Invalid, odd.fill32Async(0, .{ .r = &r, .handle = null })); + try std.testing.expectEqual(@as(u32, 0), Mock.calls); +} + +test "addresses and device copies stay inside the buffer" { + const Mock = struct { + var calls: u32 = 0; + fn copy(_: abi.DevicePtr, _: abi.DevicePtr, _: usize) callconv(.c) abi.Result { + calls += 1; + return 0; + } + fn sync(_: abi.Stream) callconv(.c) abi.Result { + return 0; + } + }; + var r: runtime.Runtime = undefined; + r.api.hipMemcpyDtoD = Mock.copy; + r.api.hipStreamSynchronize = Mock.sync; + const b: DeviceBuffer = .{ .r = &r, .ptr = @ptrFromInt(4096), .len = 64 }; + try std.testing.expectEqual(@as(u64, 4096 + 64), try b.address(64)); + try std.testing.expectError(error.Invalid, b.address(65)); + try std.testing.expectError(error.Invalid, b.copyFrom(32, 8192, 33)); + try std.testing.expectEqual(@as(u32, 0), Mock.calls); + try b.copyFrom(32, 8192, 32); + try std.testing.expectEqual(@as(u32, 1), Mock.calls); +} + +test "usage counts held bytes and the device peak" { + const before = usage(true); + count(true, 100, 0); + count(false, 7, 0); + count(true, 0, 60); + const now = usage(false); + try std.testing.expectEqual(before.device + 40, now.device); + try std.testing.expectEqual(before.host + 7, now.host); + try std.testing.expectEqual(before.device + 100, now.peak); + count(true, 0, 40); + count(false, 0, 7); + try std.testing.expectEqual(before.device, usage(true).peak); +} diff --git a/zig/src/hip/module.zig b/zig/src/hip/module.zig index 2e335206615..d8b26deee9d 100644 --- a/zig/src/hip/module.zig +++ b/zig/src/hip/module.zig @@ -25,6 +25,14 @@ pub const Module = struct { self.* = undefined; } + pub fn global(self: Module, name: [:0]const u8) runtime.Error!Global { + var ptr: abi.DevicePtr = null; + var len: usize = 0; + try runtime.check(self.r.api.hipModuleGetGlobal(&ptr, &len, self.handle, name.ptr)); + if (ptr == null or len == 0) return error.Invalid; + return .{ .address = @intFromPtr(ptr), .len = len }; + } + pub fn function(self: Module, name: [:0]const u8) runtime.Error!Function { var handle: abi.Function = null; try runtime.check(self.r.api.hipModuleGetFunction(&handle, self.handle, name.ptr)); @@ -33,7 +41,26 @@ pub const Module = struct { } }; -pub const Function = struct { r: *const runtime.Runtime, handle: abi.Function }; +pub const Function = struct { + r: *const runtime.Runtime, + handle: abi.Function, + + pub fn attribute(self: Function, a: abi.FunctionAttribute) runtime.Error!c_int { + var v: c_int = 0; + try runtime.check(self.r.api.hipFuncGetAttribute(&v, a, self.handle)); + return v; + } + + /// Blocks of `threads` threads and `shared` dynamic bytes one compute unit holds at once. + pub fn occupancy(self: Function, threads: u32, shared: usize) runtime.Error!u32 { + var n: c_int = 0; + try runtime.check(self.r.api.hipModuleOccupancyMaxActiveBlocksPerMultiprocessor(&n, self.handle, @intCast(threads), shared)); + return @intCast(@max(n, 0)); + } +}; + +/// A module-scope `__device__` variable: its device address and size. +pub const Global = struct { address: u64, len: usize }; test "unknown architecture is refused before invoking HIP" { const std = @import("std"); diff --git a/zig/src/hip/runtime.zig b/zig/src/hip/runtime.zig index 9b93bc442a3..8f5527bd844 100644 --- a/zig/src/hip/runtime.zig +++ b/zig/src/hip/runtime.zig @@ -19,6 +19,12 @@ pub const Runtime = struct { return .{ .lib = lib, .api = api }; } + /// HIP's name for a failed call's result, for logs (`hipErrorOutOfMemory` ...). + pub fn errorName(self: *const Runtime, result: abi.Result) []const u8 { + const name = self.api.hipGetErrorName(result) orelse return "unknown HIP error"; + return std.mem.span(name); + } + pub fn close(self: *Runtime) void { self.lib.close(); self.* = undefined; diff --git a/zig/src/hip/runtime_tests.zig b/zig/src/hip/runtime_tests.zig index 7d0bdececc3..2274cefacec 100644 --- a/zig/src/hip/runtime_tests.zig +++ b/zig/src/hip/runtime_tests.zig @@ -8,6 +8,7 @@ const HostBuffer = @import("memory.zig").HostBuffer; const Module = @import("module.zig").Module; const launch = @import("launch.zig"); const codeobject = @import("hip_probe"); +const probe_image: @import("code_object.zig").Image = .{ .arch = codeobject.arch, .bytes = &codeobject.bytes }; test "HIP copies fills and mixed-width kernel arguments on real GPU" { var r = try Runtime.open(); @@ -71,3 +72,225 @@ test "HIP copies fills and mixed-width kernel arguments on real GPU" { try b.download(0, std.mem.asBytes(&got)); for (got, 0..) |v, i| try std.testing.expectEqual(@as(u32, @intCast(i + 20)), v); } + +const graph = @import("graph.zig"); + +fn fillConfig(n: u32) launch.Config { + return .{ .grid = .{ .x = (n + 255) / 256 }, .block = .{ .x = 256 } }; +} + +test "device copies, word fills, mapped host memory, a module global and wave32" { + var r = try Runtime.open(); + defer r.close(); + var ctx = try Context.init(&r, 0); + defer ctx.deinit(); + var stream = try Stream.init(&r); + defer stream.deinit(); + var arch_buffer: [256]u8 = undefined; + var m = try Module.loadForArchitecture(&r, &.{probe_image}, try @import("device_arch.zig").query(&r, 0, &arch_buffer)); + defer m.unload(); + const held = @import("memory.zig").usage(true).device; + var pattern: [1024]u32 = undefined; + for (&pattern, 0..) |*p, i| p.* = @intCast(i); + var a = try DeviceBuffer.fromHost(&r, std.mem.asBytes(&pattern)); + defer a.free(); + var b = try DeviceBuffer.alloc(&r, a.len); + defer b.free(); + try std.testing.expectEqual(held + 2 * a.len, @import("memory.zig").usage(false).device); + var got: [1024]u32 = undefined; + try b.copyFrom(0, try a.address(0), a.len); + try b.download(0, std.mem.asBytes(&got)); + try std.testing.expectEqualSlices(u32, &pattern, &got); + try b.fill32(0xdeadbeef); + try b.copyFromAsync(4, try a.address(8), 8, stream); + try stream.synchronize(); + try b.download(0, std.mem.asBytes(&got)); + try std.testing.expectEqualSlices(u32, &.{ 0xdeadbeef, 2, 3, 0xdeadbeef }, got[0..4]); + try b.fill32Async(7, stream); + try stream.synchronize(); + try b.download(0, std.mem.asBytes(&got)); + for (got) |v| try std.testing.expectEqual(@as(u32, 7), v); + + // A kernel writes pinned host memory directly; no copy reads it back. + var mapped = try HostBuffer.allocMapped(&r, 1024 * @sizeOf(f32)); + defer mapped.free(); + @memset(mapped.bytes, 0); + var args: launch.Args = .{}; + try args.add(try mapped.device()); + try args.add(@as(f32, 7)); + try args.add(@as(u32, 1024)); + try launch.launch(try m.function("tf_hip_fill_f32"), fillConfig(1024), stream, &args); + try stream.synchronize(); + for (std.mem.bytesAsSlice(f32, mapped.bytes), 0..) |v, i| try std.testing.expectEqual(7 + @as(f32, @floatFromInt(i)), v); + + const table = try m.global("tf_hip_table"); + try std.testing.expectEqual(@as(usize, 16), table.len); + const values = [4]i32{ 1, 2, 3, 4 }; + try runtime_check(r.api.hipMemcpyHtoD(@ptrFromInt(table.address), std.mem.asBytes(&values), 16)); + args = .{}; + try args.add(b.ptr); + try launch.launch(try m.function("tf_hip_read_table"), .{ .grid = .{ .x = 1 }, .block = .{ .x = 4 } }, stream, &args); + try stream.synchronize(); + var doubled: [4]i32 = undefined; + try b.download(0, std.mem.asBytes(&doubled)); + try std.testing.expectEqualSlices(i32, &.{ 2, 4, 6, 8 }, &doubled); + try std.testing.expectError(error.HipFailed, m.global("tf_hip_missing")); + + try launch.launch(try m.function("tf_hip_wave"), .{ .grid = .{ .x = 1 }, .block = .{ .x = 64 } }, stream, &args); + try stream.synchronize(); + var wave: i32 = 0; + try b.download(0, std.mem.asBytes(&wave)); + try std.testing.expectEqual(@as(i32, 32), wave); +} + +const runtime_check = @import("runtime.zig").check; + +test "a captured stream replays, and its nodes take new arguments in place" { + var r = try Runtime.open(); + defer r.close(); + var ctx = try Context.init(&r, 0); + defer ctx.deinit(); + var stream = try Stream.init(&r); + defer stream.deinit(); + var arch_buffer: [256]u8 = undefined; + var m = try Module.loadForArchitecture(&r, &.{probe_image}, try @import("device_arch.zig").query(&r, 0, &arch_buffer)); + defer m.unload(); + const step = try m.function("tf_hip_step"); + var counter = try DeviceBuffer.alloc(&r, 8); + defer counter.free(); + try counter.fill8(0); + const one: launch.Config = .{ .grid = .{ .x = 1 }, .block = .{ .x = 1 } }; + try graph.beginCapture(stream, .thread_local); + try std.testing.expectEqual(@import("abi.zig").CaptureStatus.active, try graph.captureStatus(stream)); + for (1..9) |i| { + var args: launch.Args = .{}; + try args.add(counter.ptr); + try args.add(@as(u64, i)); + try launch.launch(step, one, stream, &args); + } + var captured = try graph.endCapture(stream); + defer captured.deinit(); + var buf: [16]graph.Node = undefined; + const nodes = try captured.nodes(&buf); + try std.testing.expectEqual(@as(usize, 8), nodes.len); + var total: u64 = 0; + try counter.download(0, std.mem.asBytes(&total)); + try std.testing.expectEqual(@as(u64, 0), total); + var exec = try captured.instantiate(); + defer exec.deinit(); + try exec.upload(stream); + for (0..3) |_| try exec.launchOn(stream); + try stream.synchronize(); + try counter.download(0, std.mem.asBytes(&total)); + try std.testing.expectEqual(@as(u64, 3 * 36), total); + for (nodes) |node| { + var args: launch.Args = .{}; + try args.add(counter.ptr); + try args.add(@as(u64, 10)); + try exec.setKernel(node, step, one, &args); + } + try exec.launchOn(stream); + try stream.synchronize(); + try counter.download(0, std.mem.asBytes(&total)); + try std.testing.expectEqual(@as(u64, 3 * 36 + 80), total); +} + +fn fillAxpy(g: graph.Graph, fill: @import("module.zig").Function, axpy: @import("module.zig").Function, y: DeviceBuffer, x: DeviceBuffer, base: f32, a: f32, n: u32) !void { + var fa: launch.Args = .{}; + try fa.add(y.ptr); + try fa.add(base); + try fa.add(n); + const first = try g.addKernel(&.{}, fill, fillConfig(n), &fa); + var aa: launch.Args = .{}; + try aa.add(y.ptr); + try aa.add(x.ptr); + try aa.add(a); + try aa.add(n); + _ = try g.addKernel(&.{first}, axpy, fillConfig(n), &aa); +} + +test "an explicit graph keeps its edge, updates from a same-topology graph and refuses a topology change" { + var r = try Runtime.open(); + defer r.close(); + var ctx = try Context.init(&r, 0); + defer ctx.deinit(); + var stream = try Stream.init(&r); + defer stream.deinit(); + var arch_buffer: [256]u8 = undefined; + var m = try Module.loadForArchitecture(&r, &.{probe_image}, try @import("device_arch.zig").query(&r, 0, &arch_buffer)); + defer m.unload(); + const fill = try m.function("tf_hip_fill_f32"); + const axpy = try m.function("tf_hip_axpy"); + const n: u32 = 4096; + var x = try DeviceBuffer.alloc(&r, n * 4); + defer x.free(); + var y = try DeviceBuffer.alloc(&r, n * 4); + defer y.free(); + var xa: launch.Args = .{}; + try xa.add(x.ptr); + try xa.add(@as(f32, 0)); + try xa.add(n); + try launch.launch(fill, fillConfig(n), stream, &xa); + try stream.synchronize(); + var g1 = try graph.Graph.init(&r); + defer g1.deinit(); + try fillAxpy(g1, fill, axpy, y, x, 1, 2, n); + var exec = try g1.instantiate(); + defer exec.deinit(); + try exec.launchOn(stream); + try stream.synchronize(); + var got: [n]f32 = undefined; + try y.download(0, std.mem.sliceAsBytes(&got)); + // y = 2x + (1 + i) with x = i + for (got, 0..) |v, i| try std.testing.expectEqual(3 * @as(f32, @floatFromInt(i)) + 1, v); + var g2 = try graph.Graph.init(&r); + defer g2.deinit(); + try fillAxpy(g2, fill, axpy, y, x, 5, 3, n); + try std.testing.expectEqual(@import("abi.zig").ExecUpdateResult.success, try exec.update(g2)); + try exec.launchOn(stream); + try stream.synchronize(); + try y.download(0, std.mem.sliceAsBytes(&got)); + for (got, 0..) |v, i| try std.testing.expectEqual(4 * @as(f32, @floatFromInt(i)) + 5, v); + var g3 = try graph.Graph.init(&r); + defer g3.deinit(); + try fillAxpy(g3, fill, axpy, y, x, 7, 4, n); + _ = try g3.addKernel(&.{}, fill, fillConfig(n), &xa); + try std.testing.expect(try exec.update(g3) != .success); + try exec.launchOn(stream); + try stream.synchronize(); + try y.download(0, std.mem.sliceAsBytes(&got)); + for (got, 0..) |v, i| try std.testing.expectEqual(4 * @as(f32, @floatFromInt(i)) + 5, v); +} + +test "a cooperative grid of one block a compute unit, and the device's attributes" { + var r = try Runtime.open(); + defer r.close(); + var ctx = try Context.init(&r, 0); + defer ctx.deinit(); + var stream = try Stream.init(&r); + defer stream.deinit(); + var name_buf: [256]u8 = undefined; + try std.testing.expect((try ctx.name(&name_buf)).len > 0); + try std.testing.expectEqual(@as(c_int, 32), try ctx.attribute(.warp_size)); + try std.testing.expect(try ctx.attribute(.cooperative_launch) != 0); + const cus: u32 = @intCast(try ctx.attribute(.multiprocessor_count)); + var arch_buffer: [256]u8 = undefined; + var m = try Module.loadForArchitecture(&r, &.{probe_image}, try @import("device_arch.zig").query(&r, 0, &arch_buffer)); + defer m.unload(); + const fill = try m.function("tf_hip_fill_f32"); + try std.testing.expect(try fill.occupancy(256, 0) >= 1); + try std.testing.expect(try fill.attribute(.max_threads_per_block) >= 256); + var y = try DeviceBuffer.alloc(&r, cus * 256 * 4); + defer y.free(); + var args: launch.Args = .{}; + try args.add(y.ptr); + try args.add(@as(f32, 3)); + try args.add(cus * 256); + try launch.launch(fill, .{ .grid = .{ .x = cus }, .block = .{ .x = 256 }, .cooperative = true }, stream, &args); + try stream.synchronize(); + const got = try std.testing.allocator.alloc(f32, cus * 256); + defer std.testing.allocator.free(got); + try y.download(0, std.mem.sliceAsBytes(got)); + for (got, 0..) |v, i| try std.testing.expectEqual(3 + @as(f32, @floatFromInt(i)), v); + try std.testing.expect(r.errorName(1).len > 0); +}