diff --git a/build.zig b/build.zig index 1ee381f11ca..18ebe4a581e 100644 --- a/build.zig +++ b/build.zig @@ -160,7 +160,7 @@ pub fn build(b: *std.Build) void { const api_mod = b.createModule(.{ .root_source_file = b.path("zig/src/core/engine_api.zig"), .target = target, .optimize = optimize, .link_libc = true, .imports = &.{.{ .name = "lanes", .module = lanes_mod }} }); test_step.dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = api_mod })).step); } - hip_build.steps(b, target, test_step); + hip_build.steps(b, target, optimize, build_options, test_step); exlr8_build.hostTests(b, target, test_step); const lanes_cpu = b.createModule(.{ .root_source_file = b.path("zig/src/core/lanes/lanes.zig"), .target = b.graph.host, .optimize = .debug, .link_libc = true }); const disk_cpu = b.addTest(.{ .root_module = b.createModule(.{ diff --git a/zig/build/hip.zig b/zig/build/hip.zig index 64f05a07863..21fc4ca9953 100644 --- a/zig/build/hip.zig +++ b/zig/build/hip.zig @@ -2,9 +2,10 @@ const std = @import("std"); const caps = @import("../src/hip/caps.zig"); +const exlr8_build = @import("exlr8.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 { +pub fn steps(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builtin.OptimizeMode, build_options: *std.Build.Step.Options, test_step: *std.Build.Step) void { const hip_fixtures = b.addOptions(); for ([_][]const u8{ "success", "failed", "missing" }) |kind| { const fixture_module = b.createModule(.{ .target = b.graph.host, .link_libc = true }); @@ -21,10 +22,21 @@ pub fn steps(b: *std.Build, target: std.Build.ResolvedTarget, test_step: *std.Bu .link_libc = true, }); hip_test_module.addOptions("hip_fixtures", hip_fixtures); + hip_test_module.addImport("hip_kernels", b.createModule(.{ .root_source_file = b.addWriteFiles().add("kernels.zig", stub) })); + hip_test_module.addImport("core", coreModule(b, b.graph.host)); const hip_tests = b.addTest(.{ .root_module = hip_test_module }); const run_hip_tests = b.addRunArtifact(hip_tests); test_step.dependOn(&run_hip_tests.step); b.step("hip-host-test", "HIP admission tests without GPU work").dependOn(&run_hip_tests.step); + const loader = b.addRunArtifact(b.addTest(.{ .root_module = b.createModule(.{ + .root_source_file = b.path("zig/src/families/qwen3_5/loader.zig"), + .target = b.graph.host, + .link_libc = true, + .imports = &.{.{ .name = "core", .module = coreModule(b, b.graph.host) }}, + }) })); + loader.has_side_effects = true; // TF_QWEN_DIR is not a cached input + test_step.dependOn(&loader.step); + b.step("test-qwen35", "Qwen3.5 / 3.6 checkpoint loader tests; TF_QWEN_DIR indexes a real checkpoint").dependOn(&loader.step); const hipcc = b.option([]const u8, "hipcc", "HIP compiler for model-free tests") orelse "hipcc"; const hipcc_resolved = b.findProgram(.{ .names = &.{hipcc} }) orelse hipcc; const hip_include = b.option([]const u8, "hip-include", "HIP header directory") orelse @@ -63,4 +75,142 @@ pub fn steps(b: *std.Build, target: std.Build.ResolvedTarget, test_step: *std.Bu const affine_test = b.addTest(.{ .root_module = affine_module }); b.step("hip-affine-build", "Compile affine golden GPU test without executing").dependOn(&affine_test.step); b.step("hip-affine-test", "Run exact affine golden GPU regression").dependOn(&b.addRunArtifact(affine_test).step); + const device_lib = b.option([]const u8, "hip-device-lib", "ROCm device bitcode directory (default /lib/llvm/amdgcn/bitcode; Arch: /amdgcn/bitcode)"); + const objects = kernelObjects(b, hipcc, hipcc_resolved, device_lib, hip_arch); + const kernel_module = b.createModule(.{ .root_source_file = b.path("zig/src/hip/kernel_tests.zig"), .target = target, .link_libc = true }); + kernel_module.addIncludePath(.{ .cwd_relative = hip_include }); + kernel_module.addCSourceFile(.{ .file = b.path("zig/src/hip/device_arch.c"), .flags = &.{"-D__HIP_PLATFORM_AMD__"} }); + kernel_module.addImport("hip_kernels", objects); + kernel_module.addImport("core", coreModule(b, target)); + const kernel_test = b.addTest(.{ .root_module = kernel_module }); + b.step("hip-kernel-build", "Compile the model-free kernels and their GPU tests without running them").dependOn(&kernel_test.step); + b.step("hip-kernel-test", "Every model-free kernel against its host reference on the GPU").dependOn(&b.addRunArtifact(kernel_test).step); + const stub_kernels = b.createModule(.{ .root_source_file = b.addWriteFiles().add("kernels.zig", stub) }); + const host = engineModules(b, b.graph.host, .Debug, stub_kernels, null); + test_step.dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = host.hip })).step); + test_step.dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = host.family })).step); + test_step.dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = host.native })).step); + // the GPU programs compile on any host against stub kernels, so `test` catches what only they reach + test_step.dependOn(&checksExe(b, b.graph.host, .Debug, host).step); + test_step.dependOn(&server(b, b.graph.host, host, build_options).step); + const gpu = engineModules(b, target, optimize, objects, hip_include); + b.step("tf-qwen35-test", "Qwen3.5 / 3.6 model checks on the GPU (-Dhip-arch)").dependOn(&b.addInstallArtifact(checksExe(b, target, optimize, gpu), .{}).step); + const native = server(b, target, gpu, build_options); + b.step("native-hip", "tensorfold-native with the HIP engines into zig-out/native-hip/bin (-Dhip-arch)").dependOn(&b.addInstallArtifact(native, .{ .dest_dir = .{ .override = .{ .custom = "native-hip/bin" } } }).step); +} + +/// `tf-qwen35-test`: the model checks on a real checkpoint and GPU. +fn checksExe(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builtin.OptimizeMode, e: Engine) *std.Build.Step.Compile { + return b.addExecutable(.{ .name = "tf-qwen35-test", .root_module = b.createModule(.{ + .root_source_file = b.path("zig/tests/qwen35/main.zig"), + .target = target, + .optimize = optimize, + .link_libc = true, + .imports = &.{ .{ .name = "hip", .module = e.hip }, .{ .name = "qwen3_5", .module = e.family }, .{ .name = "lanes", .module = e.lanes }, .{ .name = "npy", .module = b.createModule(.{ .root_source_file = b.path("zig/src/core/npy.zig"), .target = target, .optimize = optimize }) } }, + }) }); +} + +const Engine = struct { hip: *std.Build.Module, lanes: *std.Build.Module, api: *std.Build.Module, family: *std.Build.Module, native: *std.Build.Module }; + +/// The HIP backend, the Qwen3.5 family over it and the native engines, on `kernels` (a stub on the host). +fn engineModules(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builtin.OptimizeMode, kernels: *std.Build.Module, hip_include: ?[]const u8) Engine { + const core = coreModule(b, target); + const hip = b.createModule(.{ .root_source_file = b.path("zig/src/hip/root.zig"), .target = target, .optimize = optimize, .link_libc = true }); + hip.addImport("core", core); + hip.addImport("hip_kernels", kernels); + hip.addImport("cuda_memory", b.createModule(.{ .root_source_file = b.path("zig/src/native/cuda_memory.zig"), .target = target, .optimize = optimize })); + if (hip_include) |dir| { + hip.addIncludePath(.{ .cwd_relative = dir }); + hip.addCSourceFile(.{ .file = b.path("zig/src/hip/device_arch.c"), .flags = &.{"-D__HIP_PLATFORM_AMD__"} }); + } + const lanes = b.createModule(.{ .root_source_file = b.path("zig/src/core/lanes/lanes.zig"), .target = target, .optimize = optimize, .link_libc = true }); + const api = b.createModule(.{ .root_source_file = b.path("zig/src/core/engine_api.zig"), .target = target, .optimize = optimize, .link_libc = true, .imports = &.{.{ .name = "lanes", .module = lanes }} }); + const family = b.createModule(.{ + .root_source_file = b.path("zig/src/families/qwen3_5/hip.zig"), + .target = target, + .optimize = optimize, + .link_libc = true, + .imports = &.{ .{ .name = "hip", .module = hip }, .{ .name = "core", .module = core }, .{ .name = "lanes", .module = lanes }, .{ .name = "engine_api", .module = api } }, + }); + const native = b.createModule(.{ + .root_source_file = b.path("zig/src/native/hip.zig"), + .target = target, + .optimize = optimize, + .link_libc = true, + .imports = &.{ .{ .name = "hip", .module = hip }, .{ .name = "engine_api", .module = api }, .{ .name = "lanes", .module = lanes }, .{ .name = "qwen3_5", .module = family } }, + }); + return .{ .hip = hip, .lanes = lanes, .api = api, .family = family, .native = native }; +} + +/// The server over the HIP engines, as the CUDA build makes it: the HTTP side keeps its safety checks. +fn server(b: *std.Build, target: std.Build.ResolvedTarget, e: Engine, build_options: *std.Build.Step.Options) *std.Build.Step.Compile { + const api = e.api; + const engines = e.native; + const tokenizer = e.hip.import_table.get("core").?.import_table.get("tokenizer").?; + const template = b.createModule(.{ .root_source_file = b.path("zig/src/core/template/template.zig"), .target = target, .optimize = .ReleaseSafe, .link_libc = true }); + const exe = b.addExecutable(.{ .name = "tensorfold-native", .root_module = b.createModule(.{ + .root_source_file = b.path("zig/src/server/main.zig"), + .target = target, + .optimize = .ReleaseSafe, + .link_libc = true, + .imports = &.{ .{ .name = "engine_api", .module = api }, .{ .name = "tokenizer", .module = tokenizer }, .{ .name = "template", .module = template }, .{ .name = "native_engines", .module = engines }, .{ .name = "checkpoint_cli", .module = b.createModule(.{ .root_source_file = b.path("zig/src/cli/cli.zig"), .target = target, .optimize = .ReleaseSafe, .link_libc = true, .imports = &.{ .{ .name = "native_engines", .module = engines }, exlr8_build.cliImport(b, target, .ReleaseSafe, e.hip.import_table.get("core").?) } }) } }, + }) }); + exe.root_module.addOptions("build_options", build_options); + return exe; +} + +/// The model-free kernels' source groups, in zig/src/hip/kernels.zig's Group order. +const groups = [_][]const u8{ "ops/ops.hip", "ops/act.hip", "attention/attention.hip", "recurrence/gated_delta.hip", "attention/prefill.hip", "decode/decode.hip", "decode/plan.hip", "tiles/dot2_tiles.hip", "tiles/dot2.hip" }; + +/// What the group sources include, so an edit to one rebuilds them. +const headers = [_][]const u8{ + "attention/attention_fa.hip", "decode/pages.hpp", "decode/plan.hpp", "ops/attention.hpp", "ops/common.hpp", + "ops/draw.hpp", "ops/tp.hpp", "ops/elementwise.hpp", "ops/linear.hpp", "ops/moe.hpp", + "ops/norms.hpp", "ops/rope.hpp", "common/arch.hpp", "common/dot2.hpp", "common/vec.hpp", + "common/wmma.hpp", "quant/act.hpp", "quant/mlx.hpp", "quant/mlx_decoder.hpp", "quant/mlx_pieces.hpp", + "quant/mlx_tiles.hpp", "tiles/dot2.hpp", "tiles/epilogue.hpp", "tiles/gemm.hpp", "tiles/gemm_kp.hpp", + "tiles/matrix_gemm.hpp", "tiles/plan.hpp", "tiles/stream.hpp", +}; + +/// The flags of the kernels' first build: no contraction, wave32 on RDNA, C++20. +const flags = [_][]const u8{ "-D__HIP_PLATFORM_AMD__=1", "-DUSE_ROCM=1", "-DHIPBLAS_V2", "-fPIC", "-DCUDA_HAS_FP16=1", "-DHIP_ENABLE_WARP_SYNC_BUILTINS=1", "-std=c++20", "-fno-gpu-rdc", "-mno-wavefrontsize64", "-ffp-contract=off" }; + +const stub = "pub const arch = \"\";\npub const images: [9][]align(8) const u8 = @splat(&.{});\n"; + +/// One code object a group for `arch`, built with the caps table's instruction switches, as the `hip_kernels` module. +fn kernelObjects(b: *std.Build, hipcc: []const u8, hipcc_resolved: []const u8, device_lib: ?[]const u8, arch: []const u8) *std.Build.Module { + const c = caps.Caps.of(arch).?; + const root = std.fs.path.dirname(std.fs.path.dirname(hipcc_resolved) orelse ".") orelse "."; + const files = b.addWriteFiles(); + var decls: []const u8 = ""; + var refs: []const u8 = ""; + for (groups, 0..) |source, i| { + const run = b.addSystemCommand(&.{ hipcc, "--genco" }); + run.addArgs(&flags); + run.addArg(b.fmt("-DTF_WAVE={d}", .{c.wave})); + run.addArg(b.fmt("-DTF_DOT2_F16={d}", .{@intFromBool(c.dot2_f16)})); + run.addArg(b.fmt("-DTF_DOT2_BF16={d}", .{@intFromBool(c.dot2_bf16)})); + run.addArg(b.fmt("-DTF_SDOT4={d}", .{@intFromBool(c.sdot4)})); + run.addArg(b.fmt("-DTF_SDOT8={d}", .{@intFromBool(c.sdot8)})); + run.addArg(b.fmt("-DTF_MATRIX={d}", .{@intFromBool(c.matrix != .none)})); + run.addArg(b.fmt("--rocm-path={s}", .{root})); + run.addArg(b.fmt("--rocm-device-lib-path={s}", .{device_lib orelse b.fmt("{s}/lib/llvm/amdgcn/bitcode", .{root})})); + run.addArg(b.fmt("--offload-arch={s}", .{arch})); + run.addPrefixedDirectoryArg("-I", b.path("zig/kernels/hip")); + for (headers) |h| run.addFileInput(b.path(b.fmt("zig/kernels/hip/{s}", .{h}))); + run.addArg("-o"); + const object = run.addOutputFileArg(b.fmt("group{d}.hsaco", .{i})); + run.addFileArg(b.path(b.fmt("zig/kernels/hip/{s}", .{source}))); + _ = files.addCopyFile(object, b.fmt("group{d}.hsaco", .{i})); + decls = b.fmt("{s}const g{d} align(8) = @embedFile(\"group{d}.hsaco\").*;\n", .{ decls, i, i }); + refs = b.fmt("{s}&g{d}, ", .{ refs, i }); + } + return b.createModule(.{ .root_source_file = files.add("kernels.zig", b.fmt("pub const arch = \"{s}\";\n{s}pub const images = [_][]align(8) const u8{{ {s}}};\n", .{ arch, decls, refs })) }); +} + +/// The backend-neutral core (checkpoint formats, the kernel registry), as the other backends import it. +fn coreModule(b: *std.Build, target: std.Build.ResolvedTarget) *std.Build.Module { + const core = b.createModule(.{ .root_source_file = b.path("zig/src/core/root.zig"), .target = target, .link_libc = true }); + core.addImport("tokenizer", b.createModule(.{ .root_source_file = b.path("zig/src/core/tokenizer/tokenizer.zig"), .target = target, .link_libc = true })); + return core; } diff --git a/zig/kernels/hip/attention/attention.hip b/zig/kernels/hip/attention/attention.hip new file mode 100644 index 00000000000..e4c8afa2c8f --- /dev/null +++ b/zig/kernels/hip/attention/attention.hip @@ -0,0 +1,236 @@ +// Causal attention, fp32 scores and softmax; KV heads are read as head / (heads / kv_heads), never repeated. + +#include +#include +#include + +#include "attention_fa.hip" + +namespace tf { +namespace rocm { + +__device__ float lane0_sum(float x) { +#pragma unroll + for (int mask = 16; mask > 0; mask >>= 1) x += __shfl_xor(x, mask, 32); + return __shfl(x, 0, 32); +} + +template +__device__ float row_dot(const float* qreg, const Cache* row, int d, int lane) { + float partial = 0.f; +#pragma unroll + for (int i = 0; i < 8; ++i) { + int idx = lane + i * 32; + if (idx < d) partial += qreg[i] * static_cast(row[idx]); + } + return lane0_sum(partial); +} + +template +__global__ void __launch_bounds__(32) +causal_kernel(const float* __restrict__ q, const Cache* __restrict__ k, const Cache* __restrict__ v, + float* __restrict__ out, int qlen, int span, int heads, int kv_heads, int d, float scale, int q_pos0, + long long k_sb, long long k_sh, long long k_ss, long long v_sb, long long v_sh, long long v_ss) { + int qi = blockIdx.x; + int head = blockIdx.y; + int batch = blockIdx.z; + if (qi >= qlen) return; + int lane = threadIdx.x; + int kv = head / (heads / kv_heads); + int visible = q_pos0 + qi + 1; + if (visible > span) visible = span; + + const float* qrow = q + ((static_cast(batch) * heads + head) * qlen + qi) * d; + float qreg[8] = {}; +#pragma unroll + for (int i = 0; i < 8; ++i) { + int idx = lane + i * 32; + if (idx < d) qreg[i] = qrow[idx]; + } + + const Cache* kbase = k + batch * k_sb + kv * k_sh; + const Cache* vbase = v + batch * v_sb + kv * v_sh; + float max_score = -INFINITY; + for (int key = 0; key < visible; ++key) { + float score = row_dot(qreg, kbase + key * k_ss, d, lane) * scale; + max_score = fmaxf(max_score, score); + } + float denom = 0.f; + for (int key = 0; key < visible; ++key) { + float score = row_dot(qreg, kbase + key * k_ss, d, lane) * scale; + denom += expf(score - max_score); + } + float acc[8] = {}; + for (int key = 0; key < visible; ++key) { + float score = row_dot(qreg, kbase + key * k_ss, d, lane) * scale; + float weight = expf(score - max_score) / denom; +#pragma unroll + for (int i = 0; i < 8; ++i) { + int idx = lane + i * 32; + if (idx < d) acc[i] += weight * static_cast((vbase + key * v_ss)[idx]); + } + } + float* orow = out + ((static_cast(batch) * heads + head) * qlen + qi) * d; +#pragma unroll + for (int i = 0; i < 8; ++i) { + int idx = lane + i * 32; + if (idx < d) orow[idx] = acc[i]; + } +} + +} // namespace rocm +} // namespace tf + +// Decode: a warp scores a key, a block per head reduces the softmax, then V streams in 128-key tiles. +template +__global__ void score_keys(const float* __restrict__ q, const Cache* __restrict__ k, float* __restrict__ scores, + int span, int heads, int kv_heads, int d, float scale, int visible, long long k_sb, + long long k_sh, long long k_ss, const int* pos) { + if (pos != nullptr) visible = min(pos[blockIdx.z] + 1, span); + int lane = threadIdx.x & 31; + int key = blockIdx.x * (blockDim.x >> 5) + (threadIdx.x >> 5); + int head = blockIdx.y; + int batch = blockIdx.z; + const float* qrow = q + (static_cast(batch) * heads + head) * d; + float qreg[8]; +#pragma unroll + for (int i = 0; i < 8; ++i) { + int idx = lane + i * 32; + qreg[i] = idx < d ? qrow[idx] : 0.f; + } + float partial = 0.f; + if (key < visible) { + int kv = head / (heads / kv_heads); + const Cache* krow = k + batch * k_sb + static_cast(kv) * k_sh + static_cast(key) * k_ss; +#pragma unroll + for (int i = 0; i < 8; ++i) { + int idx = lane + i * 32; + if (idx < d) partial += qreg[i] * static_cast(krow[idx]); + } + } + float dot = tf::rocm::lane0_sum(partial); + if (lane == 0 && key < span) { + float score = key < visible ? dot * scale : -INFINITY; + scores[(static_cast(batch) * heads + head) * span + key] = score; + } +} + +extern "C" __global__ void tf_softmax_stats(const float* __restrict__ scores, float* __restrict__ stats, int span, + int visible, const int* pos) { + if (pos != nullptr) visible = min(pos[blockIdx.y] + 1, span); + int head = blockIdx.x; + int batch = blockIdx.y; + const float* row = scores + (static_cast(batch) * gridDim.x + head) * span; + float local = -INFINITY; + for (int i = threadIdx.x; i < visible; i += blockDim.x) local = fmaxf(local, row[i]); + __shared__ float buf[256]; + buf[threadIdx.x] = local; + __syncthreads(); + for (int step = blockDim.x >> 1; step > 0; step >>= 1) { + if (threadIdx.x < step) buf[threadIdx.x] = fmaxf(buf[threadIdx.x], buf[threadIdx.x + step]); + __syncthreads(); + } + float max_score = buf[0]; + __syncthreads(); + local = 0.f; + for (int i = threadIdx.x; i < visible; i += blockDim.x) local += expf(row[i] - max_score); + buf[threadIdx.x] = local; + __syncthreads(); + for (int step = blockDim.x >> 1; step > 0; step >>= 1) { + if (threadIdx.x < step) buf[threadIdx.x] += buf[threadIdx.x + step]; + __syncthreads(); + } + if (threadIdx.x == 0) { + float* dest = stats + (static_cast(batch) * gridDim.x + head) * 2; + dest[0] = max_score; + dest[1] = buf[0]; + } +} + +template +__global__ void apply_values(const float* __restrict__ scores, const float* __restrict__ stats, + const Cache* __restrict__ v, float* __restrict__ partials, int span, int heads, + int kv_heads, int d, int visible, long long v_sb, long long v_sh, long long v_ss, + const int* pos) { + if (pos != nullptr) visible = min(pos[blockIdx.z] + 1, span); + int tile = blockIdx.x; + int head = blockIdx.y; + int batch = blockIdx.z; + int lane = threadIdx.x; + int key0 = tile * 128; + if (lane >= d) return; + if (key0 >= visible) { // a tile past the keys in use (the graph's grid covers the whole cache) adds zero + partials[(((static_cast(batch) * heads + head) * gridDim.x) + tile) * d + lane] = 0.f; + return; + } + int kv = head / (heads / kv_heads); + const float* row = scores + (static_cast(batch) * heads + head) * span; + float max_score = stats[(static_cast(batch) * heads + head) * 2]; + float denom = stats[(static_cast(batch) * heads + head) * 2 + 1]; + const Cache* base = v + batch * v_sb + static_cast(kv) * v_sh + lane; + float acc = 0.f; + int stop = key0 + 128; + if (stop > visible) stop = visible; + for (int key = key0; key < stop; ++key) { + float weight = expf(row[key] - max_score) / denom; + acc += weight * static_cast(base[static_cast(key) * v_ss]); + } + int tiles = gridDim.x; + partials[(((static_cast(batch) * heads + head) * tiles) + tile) * d + lane] = acc; +} + +extern "C" __global__ void tf_sum_partials(const float* __restrict__ partials, float* __restrict__ out, int tiles, + int d) { + int head = blockIdx.x; + int batch = blockIdx.y; + int lane = threadIdx.x; + if (lane >= d) return; + const float* col = partials + ((static_cast(batch) * gridDim.x + head) * tiles) * d + lane; + float acc = 0.f; + for (int tile = 0; tile < tiles; ++tile) acc += col[static_cast(tile) * d]; + out[(static_cast(batch) * gridDim.x + head) * d + lane] = acc; +} + +// The template kernels launches.zig resolves. +template __global__ void tf::rocm::causal_kernel<__half>(const float* __restrict__ q, const __half* __restrict__ k, + const __half* __restrict__ v, float* __restrict__ out, int qlen, int span, int heads, int kv_heads, int d, + float scale, int q_pos0, long long k_sb, long long k_sh, long long k_ss, long long v_sb, long long v_sh, + long long v_ss); +template __global__ void tf::rocm::causal_kernel(const float* __restrict__ q, + const hip_bfloat16* __restrict__ k, const hip_bfloat16* __restrict__ v, float* __restrict__ out, int qlen, int span, + int heads, int kv_heads, int d, float scale, int q_pos0, long long k_sb, long long k_sh, long long k_ss, + long long v_sb, long long v_sh, long long v_ss); +template __global__ void tf::rocm::causal_kernel(const float* __restrict__ q, const float* __restrict__ k, + const float* __restrict__ v, float* __restrict__ out, int qlen, int span, int heads, int kv_heads, int d, + float scale, int q_pos0, long long k_sb, long long k_sh, long long k_ss, long long v_sb, long long v_sh, + long long v_ss); +template __global__ void score_keys<__half>(const float* __restrict__ q, const __half* __restrict__ k, + float* __restrict__ scores, int span, int heads, int kv_heads, int d, float scale, int visible, long long k_sb, + long long k_sh, long long k_ss, const int* pos); +template __global__ void score_keys(const float* __restrict__ q, const hip_bfloat16* __restrict__ k, + float* __restrict__ scores, int span, int heads, int kv_heads, int d, float scale, int visible, long long k_sb, + long long k_sh, long long k_ss, const int* pos); +template __global__ void score_keys(const float* __restrict__ q, const float* __restrict__ k, + float* __restrict__ scores, int span, int heads, int kv_heads, int d, float scale, int visible, long long k_sb, + long long k_sh, long long k_ss, const int* pos); +template __global__ void apply_values<__half>(const float* __restrict__ scores, const float* __restrict__ stats, + const __half* __restrict__ v, float* __restrict__ partials, int span, int heads, int kv_heads, int d, int visible, + long long v_sb, long long v_sh, long long v_ss, const int* pos); +template __global__ void apply_values(const float* __restrict__ scores, const float* __restrict__ stats, + const hip_bfloat16* __restrict__ v, float* __restrict__ partials, int span, int heads, int kv_heads, int d, + int visible, long long v_sb, long long v_sh, long long v_ss, const int* pos); +template __global__ void apply_values(const float* __restrict__ scores, const float* __restrict__ stats, + const float* __restrict__ v, float* __restrict__ partials, int span, int heads, int kv_heads, int d, int visible, + long long v_sb, long long v_sh, long long v_ss, const int* pos); +template __global__ void tf::rocm::fa_prefill<__half, 64>(const float* __restrict__ q, const __half* __restrict__ k, + const __half* __restrict__ v, float* __restrict__ out, int qlen, int span, int heads, int kv_heads, int d, + float scale, int q_pos0, long long k_sb, long long k_sh, long long k_ss, long long v_sb, long long v_sh, + long long v_ss); +template __global__ void tf::rocm::fa_prefill(const float* __restrict__ q, + const hip_bfloat16* __restrict__ k, const hip_bfloat16* __restrict__ v, float* __restrict__ out, int qlen, int span, + int heads, int kv_heads, int d, float scale, int q_pos0, long long k_sb, long long k_sh, long long k_ss, + long long v_sb, long long v_sh, long long v_ss); +template __global__ void tf::rocm::fa_prefill(const float* __restrict__ q, const float* __restrict__ k, + const float* __restrict__ v, float* __restrict__ out, int qlen, int span, int heads, int kv_heads, int d, + float scale, int q_pos0, long long k_sb, long long k_sh, long long k_ss, long long v_sb, long long v_sh, + long long v_ss); diff --git a/zig/kernels/hip/attention/attention_fa.hip b/zig/kernels/hip/attention/attention_fa.hip new file mode 100644 index 00000000000..f5bb6baca22 --- /dev/null +++ b/zig/kernels/hip/attention/attention_fa.hip @@ -0,0 +1,462 @@ +// Flash Attention 2 prefill: a block owns 16 query rows and walks the keys in order with an online softmax. + +#include +#include +#include + +#include + +namespace tf { +namespace rocm { + +constexpr int kFaThreads = 256; +constexpr int kFaBc = 32; +constexpr int kFaMaxD = 256; + +// The query stays fp32 and the keys widen in the product: dot2 would round the query. +template +using fa_q_t = float; + +__device__ __forceinline__ __half fa_store(__half, float x) { return __float2half(x); } +__device__ __forceinline__ hip_bfloat16 fa_store(hip_bfloat16, float x) { return hip_bfloat16(x); } +__device__ __forceinline__ float fa_store(float, float x) { return x; } + +template +__host__ __device__ constexpr int fa_ld() { + // Pad so 32 keys at one column sit in 32 different banks. The row itself stays contiguous. + return sizeof(T) == 4 ? 257 : 258; +} + +template +__device__ __forceinline__ float fa_dot_half(const __half* q, const __half* k) { + const __half2* qq = reinterpret_cast(q); + const __half2* kk = reinterpret_cast(k); + float a0 = 0.f, a1 = 0.f, a2 = 0.f, a3 = 0.f; +#pragma unroll 8 + for (int p = 0; p < D / 2; p += 4) { + a0 = __builtin_amdgcn_fdot2(qq[p], kk[p], a0, false); + a1 = __builtin_amdgcn_fdot2(qq[p + 1], kk[p + 1], a1, false); + a2 = __builtin_amdgcn_fdot2(qq[p + 2], kk[p + 2], a2, false); + a3 = __builtin_amdgcn_fdot2(qq[p + 3], kk[p + 3], a3, false); + } + return (a0 + a1) + (a2 + a3); +} + +__device__ __forceinline__ float fa_dot_half(const __half* q, const __half* k, int d) { + const __half2* qq = reinterpret_cast(q); + const __half2* kk = reinterpret_cast(k); + int pairs = d >> 1; + float a0 = 0.f, a1 = 0.f, a2 = 0.f, a3 = 0.f; + int p = 0; + for (; p + 4 <= pairs; p += 4) { + a0 = __builtin_amdgcn_fdot2(qq[p], kk[p], a0, false); + a1 = __builtin_amdgcn_fdot2(qq[p + 1], kk[p + 1], a1, false); + a2 = __builtin_amdgcn_fdot2(qq[p + 2], kk[p + 2], a2, false); + a3 = __builtin_amdgcn_fdot2(qq[p + 3], kk[p + 3], a3, false); + } + float acc = (a0 + a1) + (a2 + a3); + for (; p < pairs; ++p) acc = __builtin_amdgcn_fdot2(qq[p], kk[p], acc, false); + return acc; +} + +template +__device__ __forceinline__ void fa_dot_bf2(const float* q0, const float* q1, const hip_bfloat16* k, float& acc0, + float& acc1) { + float a0 = 0.f, a1 = 0.f, a2 = 0.f, a3 = 0.f; + float b0 = 0.f, b1 = 0.f, b2 = 0.f, b3 = 0.f; +#pragma unroll 8 + for (int dim = 0; dim < D; dim += 4) { + float k0 = static_cast(k[dim]); + float k1 = static_cast(k[dim + 1]); + float k2 = static_cast(k[dim + 2]); + float k3 = static_cast(k[dim + 3]); + a0 = fmaf(q0[dim], k0, a0); + b0 = fmaf(q1[dim], k0, b0); + a1 = fmaf(q0[dim + 1], k1, a1); + b1 = fmaf(q1[dim + 1], k1, b1); + a2 = fmaf(q0[dim + 2], k2, a2); + b2 = fmaf(q1[dim + 2], k2, b2); + a3 = fmaf(q0[dim + 3], k3, a3); + b3 = fmaf(q1[dim + 3], k3, b3); + } + acc0 = (a0 + a1) + (a2 + a3); + acc1 = (b0 + b1) + (b2 + b3); +} + +template +__device__ __forceinline__ float fa_dot_bf(const float* q, const hip_bfloat16* k) { + float a0 = 0.f, a1 = 0.f, a2 = 0.f, a3 = 0.f; +#pragma unroll 8 + for (int dim = 0; dim < D; dim += 4) { + a0 = fmaf(q[dim], static_cast(k[dim]), a0); + a1 = fmaf(q[dim + 1], static_cast(k[dim + 1]), a1); + a2 = fmaf(q[dim + 2], static_cast(k[dim + 2]), a2); + a3 = fmaf(q[dim + 3], static_cast(k[dim + 3]), a3); + } + return (a0 + a1) + (a2 + a3); +} + +__device__ __forceinline__ float fa_dot_bf(const float* q, const hip_bfloat16* k, int d) { + float a0 = 0.f, a1 = 0.f, a2 = 0.f, a3 = 0.f; + int dim = 0; + for (; dim + 4 <= d; dim += 4) { + a0 = fmaf(q[dim], static_cast(k[dim]), a0); + a1 = fmaf(q[dim + 1], static_cast(k[dim + 1]), a1); + a2 = fmaf(q[dim + 2], static_cast(k[dim + 2]), a2); + a3 = fmaf(q[dim + 3], static_cast(k[dim + 3]), a3); + } + float acc = (a0 + a1) + (a2 + a3); + for (; dim < d; ++dim) acc = fmaf(q[dim], static_cast(k[dim]), acc); + return acc; +} + +template +__device__ __forceinline__ float fa_dot_f(const float* q, const float* k) { + float a0 = 0.f, a1 = 0.f, a2 = 0.f, a3 = 0.f; +#pragma unroll 8 + for (int dim = 0; dim < D; dim += 4) { + a0 = fmaf(q[dim], k[dim], a0); + a1 = fmaf(q[dim + 1], k[dim + 1], a1); + a2 = fmaf(q[dim + 2], k[dim + 2], a2); + a3 = fmaf(q[dim + 3], k[dim + 3], a3); + } + return (a0 + a1) + (a2 + a3); +} + +__device__ __forceinline__ float fa_dot_f(const float* q, const float* k, int d) { + float a0 = 0.f, a1 = 0.f, a2 = 0.f, a3 = 0.f; + int dim = 0; + for (; dim + 4 <= d; dim += 4) { + a0 = fmaf(q[dim], k[dim], a0); + a1 = fmaf(q[dim + 1], k[dim + 1], a1); + a2 = fmaf(q[dim + 2], k[dim + 2], a2); + a3 = fmaf(q[dim + 3], k[dim + 3], a3); + } + float acc = (a0 + a1) + (a2 + a3); + for (; dim < d; ++dim) acc = fmaf(q[dim], k[dim], acc); + return acc; +} + +template +__device__ __forceinline__ float fa_qk(const __half* q, const __half* k, int d) { + if constexpr (DSpec == 256) return fa_dot_half<256>(q, k); + return fa_dot_half(q, k, d); +} + +template +__device__ __forceinline__ float fa_qk(const float* q, const hip_bfloat16* k, int d) { + if constexpr (DSpec == 256) return fa_dot_bf<256>(q, k); + return fa_dot_bf(q, k, d); +} + +template +__device__ __forceinline__ float fa_qk(const float* q, const float* k, int d) { + if constexpr (DSpec == 256) return fa_dot_f<256>(q, k); + return fa_dot_f(q, k, d); +} + +template +__device__ __forceinline__ void fa_pair_half(const __half* q, const __half* k0, const __half* k1, int d, float& s0, + float& s1) { + const __half2* qq = reinterpret_cast(q); + const __half2* a = reinterpret_cast(k0); + const __half2* b = reinterpret_cast(k1); + float a0 = 0.f, a1 = 0.f, a2 = 0.f, a3 = 0.f; + float b0 = 0.f, b1 = 0.f, b2 = 0.f, b3 = 0.f; + int pairs = d >> 1; + int p = 0; +#pragma unroll 8 + for (; p + 4 <= pairs; p += 4) { + __half2 q0 = qq[p]; + __half2 q1 = qq[p + 1]; + __half2 q2 = qq[p + 2]; + __half2 q3 = qq[p + 3]; + a0 = __builtin_amdgcn_fdot2(q0, a[p], a0, false); + a1 = __builtin_amdgcn_fdot2(q1, a[p + 1], a1, false); + a2 = __builtin_amdgcn_fdot2(q2, a[p + 2], a2, false); + a3 = __builtin_amdgcn_fdot2(q3, a[p + 3], a3, false); + if constexpr (Bc == 64) { + b0 = __builtin_amdgcn_fdot2(q0, b[p], b0, false); + b1 = __builtin_amdgcn_fdot2(q1, b[p + 1], b1, false); + b2 = __builtin_amdgcn_fdot2(q2, b[p + 2], b2, false); + b3 = __builtin_amdgcn_fdot2(q3, b[p + 3], b3, false); + } + } + s0 = (a0 + a1) + (a2 + a3); + s1 = (b0 + b1) + (b2 + b3); + for (; p < pairs; ++p) { + __half2 qv = qq[p]; + s0 = __builtin_amdgcn_fdot2(qv, a[p], s0, false); + if constexpr (Bc == 64) s1 = __builtin_amdgcn_fdot2(qv, b[p], s1, false); + } +} + +template +__device__ __forceinline__ void fa_pair_hf(const float* q, const __half* k0, const __half* k1, int d, float& s0, + float& s1) { + float a0 = 0.f, a1 = 0.f, a2 = 0.f, a3 = 0.f; + float b0 = 0.f, b1 = 0.f, b2 = 0.f, b3 = 0.f; + int dim = 0; +#pragma unroll 8 + for (; dim + 4 <= d; dim += 4) { + float q0 = q[dim]; + float q1 = q[dim + 1]; + float q2 = q[dim + 2]; + float q3 = q[dim + 3]; + a0 = fmaf(q0, __half2float(k0[dim]), a0); + a1 = fmaf(q1, __half2float(k0[dim + 1]), a1); + a2 = fmaf(q2, __half2float(k0[dim + 2]), a2); + a3 = fmaf(q3, __half2float(k0[dim + 3]), a3); + if constexpr (Bc == 64) { + b0 = fmaf(q0, __half2float(k1[dim]), b0); + b1 = fmaf(q1, __half2float(k1[dim + 1]), b1); + b2 = fmaf(q2, __half2float(k1[dim + 2]), b2); + b3 = fmaf(q3, __half2float(k1[dim + 3]), b3); + } + } + s0 = (a0 + a1) + (a2 + a3); + s1 = (b0 + b1) + (b2 + b3); + for (; dim < d; ++dim) { + s0 = fmaf(q[dim], __half2float(k0[dim]), s0); + if constexpr (Bc == 64) s1 = fmaf(q[dim], __half2float(k1[dim]), s1); + } +} + +template +__device__ __forceinline__ void fa_pair_bf(const float* q, const hip_bfloat16* k0, const hip_bfloat16* k1, int d, + float& s0, float& s1) { + float a0 = 0.f, a1 = 0.f, a2 = 0.f, a3 = 0.f; + float b0 = 0.f, b1 = 0.f, b2 = 0.f, b3 = 0.f; + int dim = 0; +#pragma unroll 8 + for (; dim + 4 <= d; dim += 4) { + float q0 = q[dim]; + float q1 = q[dim + 1]; + float q2 = q[dim + 2]; + float q3 = q[dim + 3]; + a0 = fmaf(q0, static_cast(k0[dim]), a0); + a1 = fmaf(q1, static_cast(k0[dim + 1]), a1); + a2 = fmaf(q2, static_cast(k0[dim + 2]), a2); + a3 = fmaf(q3, static_cast(k0[dim + 3]), a3); + if constexpr (Bc == 64) { + b0 = fmaf(q0, static_cast(k1[dim]), b0); + b1 = fmaf(q1, static_cast(k1[dim + 1]), b1); + b2 = fmaf(q2, static_cast(k1[dim + 2]), b2); + b3 = fmaf(q3, static_cast(k1[dim + 3]), b3); + } + } + s0 = (a0 + a1) + (a2 + a3); + s1 = (b0 + b1) + (b2 + b3); + for (; dim < d; ++dim) { + s0 = fmaf(q[dim], static_cast(k0[dim]), s0); + if constexpr (Bc == 64) s1 = fmaf(q[dim], static_cast(k1[dim]), s1); + } +} + +template +__device__ __forceinline__ void fa_pair_f(const float* q, const float* k0, const float* k1, int d, float& s0, + float& s1) { + float a0 = 0.f, a1 = 0.f, a2 = 0.f, a3 = 0.f; + float b0 = 0.f, b1 = 0.f, b2 = 0.f, b3 = 0.f; + int dim = 0; +#pragma unroll 8 + for (; dim + 4 <= d; dim += 4) { + float q0 = q[dim]; + float q1 = q[dim + 1]; + float q2 = q[dim + 2]; + float q3 = q[dim + 3]; + a0 = fmaf(q0, k0[dim], a0); + a1 = fmaf(q1, k0[dim + 1], a1); + a2 = fmaf(q2, k0[dim + 2], a2); + a3 = fmaf(q3, k0[dim + 3], a3); + if constexpr (Bc == 64) { + b0 = fmaf(q0, k1[dim], b0); + b1 = fmaf(q1, k1[dim + 1], b1); + b2 = fmaf(q2, k1[dim + 2], b2); + b3 = fmaf(q3, k1[dim + 3], b3); + } + } + s0 = (a0 + a1) + (a2 + a3); + s1 = (b0 + b1) + (b2 + b3); + for (; dim < d; ++dim) { + s0 = fmaf(q[dim], k0[dim], s0); + if constexpr (Bc == 64) s1 = fmaf(q[dim], k1[dim], s1); + } +} + +template +__device__ void fa_load_tile(Cache* dst, const Cache* src, int k0, int span, int d, long long stride, int tid) { + constexpr int ld = fa_ld(); + const bool vec8 = sizeof(Cache) == 2 && (d % 8) == 0 && (stride % 8) == 0 && + (reinterpret_cast(src) & 15u) == 0; + if (vec8) { + int chunks = d >> 3; + for (int e = tid; e < Bc * chunks; e += kFaThreads) { + int key = e / chunks; + int chunk = e - key * chunks; + unsigned bits0 = 0, bits1 = 0, bits2 = 0, bits3 = 0; + if (k0 + key < span) { + const unsigned* g = reinterpret_cast( + src + (static_cast(k0 + key) * stride) + chunk * 8); + bits0 = g[0]; + bits1 = g[1]; + bits2 = g[2]; + bits3 = g[3]; + } + unsigned* slot = reinterpret_cast(dst + key * ld + chunk * 8); + slot[0] = bits0; + slot[1] = bits1; + slot[2] = bits2; + slot[3] = bits3; + } + return; + } + for (int e = tid; e < Bc * d; e += kFaThreads) { + int key = e / d; + int dim = e - key * d; + float raw = 0.f; + if (k0 + key < span) raw = static_cast(src[(static_cast(k0 + key) * stride) + dim]); + dst[key * ld + dim] = fa_store(Cache{}, raw); + } +} + +template +__global__ void __launch_bounds__(kFaThreads, 1) +fa_prefill(const float* __restrict__ q, const Cache* __restrict__ k, const Cache* __restrict__ v, + float* __restrict__ out, int qlen, int span, int heads, int kv_heads, int d, float scale, int q_pos0, + long long k_sb, long long k_sh, long long k_ss, long long v_sb, long long v_sh, long long v_ss) { + constexpr int kBr = 16; + constexpr int kWarps = kFaThreads / 32; + constexpr int kQLd = fa_ld>(); + constexpr int kKLd = fa_ld(); + __shared__ alignas(16) fa_q_t sQ[kBr * kQLd]; + __shared__ alignas(16) Cache sK[Bc * kKLd]; + __shared__ float sP[kBr * Bc]; + __shared__ float sM[kBr]; + __shared__ float sL[kBr]; + __shared__ float sA[kBr]; + + int q0 = blockIdx.x * kBr; + int head = blockIdx.y; + int batch = blockIdx.z; + if (q0 >= qlen) return; + int tid = threadIdx.x; + int warp = tid >> 5; + int lane = tid & 31; + int q_hi = qlen - q0; + if (q_hi > kBr) q_hi = kBr; + int max_vis = q_pos0 + q0 + q_hi; + if (max_vis > span) max_vis = span; + int kv = head / (heads / kv_heads); + + const float* qrows = q + ((static_cast(batch) * heads + head) * qlen + q0) * d; + float* orows = out + ((static_cast(batch) * heads + head) * qlen + q0) * d; + const Cache* kbase = k + static_cast(batch) * k_sb + static_cast(kv) * k_sh; + const Cache* vbase = v + static_cast(batch) * v_sb + static_cast(kv) * v_sh; + + for (int e = tid; e < kBr * d; e += kFaThreads) { + int row = e / d; + int dim = e - row * d; + sQ[row * kQLd + dim] = row < q_hi ? qrows[row * d + dim] : 0.f; + } + float oreg[kBr]; +#pragma unroll + for (int row = 0; row < kBr; ++row) oreg[row] = 0.f; + if (tid < kBr) { + sM[tid] = -INFINITY; + sL[tid] = 0.f; + sA[tid] = 1.f; + } + __syncthreads(); + + for (int k0 = 0; k0 < max_vis; k0 += Bc) { + fa_load_tile(sK, kbase, k0, span, d, k_ss, tid); + __syncthreads(); +#pragma unroll 1 + for (int iter = 0; iter < kBr / kWarps; ++iter) { + int row = warp + iter * kWarps; + float s0 = 0.f, s1 = 0.f; + if (row < q_hi) { + const Cache* key0 = sK + lane * kKLd; + const Cache* key1 = Bc == 64 ? sK + (lane + 32) * kKLd : key0; + if constexpr (std::is_same_v) + fa_pair_hf(sQ + row * kQLd, key0, key1, d, s0, s1); + else if constexpr (std::is_same_v) + fa_pair_bf(sQ + row * kQLd, key0, key1, d, s0, s1); + else + fa_pair_f(sQ + row * kQLd, key0, key1, d, s0, s1); + s0 *= scale; + s1 *= scale; + int vis = q_pos0 + q0 + row + 1; + if (vis > span) vis = span; + if (k0 + lane >= vis) s0 = -INFINITY; + if (k0 + lane + 32 >= vis) s1 = -INFINITY; + } + if (row < kBr) { + sP[row * Bc + lane] = s0; + if constexpr (Bc == 64) sP[row * Bc + lane + 32] = s1; + } + } + __syncthreads(); + if (tid < kBr) { + int row = tid; + if (row >= q_hi) { + sA[row] = 1.f; + for (int key = 0; key < Bc; ++key) sP[row * Bc + key] = 0.f; + } else { + float tile_max = -INFINITY; + bool any = false; + for (int key = 0; key < Bc; ++key) { + float score = sP[row * Bc + key]; + if (score != -INFINITY) { + tile_max = fmaxf(tile_max, score); + any = true; + } + } + if (!any) { + sA[row] = 1.f; + for (int key = 0; key < Bc; ++key) sP[row * Bc + key] = 0.f; + } else { + float next_m = fmaxf(sM[row], tile_max); + float alpha = sM[row] == -INFINITY ? 0.f : expf(sM[row] - next_m); + float sum = 0.f; + for (int key = 0; key < Bc; ++key) { + float score = sP[row * Bc + key]; + float prob = score == -INFINITY ? 0.f : expf(score - next_m); + sP[row * Bc + key] = prob; + sum += prob; + } + sL[row] = fmaf(alpha, sL[row], sum); + sM[row] = next_m; + sA[row] = alpha; + } + } + } + __syncthreads(); + fa_load_tile(sK, vbase, k0, span, d, v_ss, tid); + __syncthreads(); + if (tid < d) { + float pv[kBr]; +#pragma unroll + for (int row = 0; row < kBr; ++row) pv[row] = 0.f; + for (int key = 0; key < Bc; ++key) { + float vv = static_cast(sK[key * kKLd + tid]); +#pragma unroll + for (int row = 0; row < kBr; ++row) pv[row] = fmaf(sP[row * Bc + key], vv, pv[row]); + } +#pragma unroll + for (int row = 0; row < kBr; ++row) oreg[row] = fmaf(sA[row], oreg[row], pv[row]); + } + __syncthreads(); + } + + if (tid < d) { + for (int row = 0; row < q_hi; ++row) { + float inv = sL[row] == 0.f ? 0.f : 1.f / sL[row]; + orows[row * d + tid] = oreg[row] * inv; + } + } +} + +} // namespace rocm +} // namespace tf diff --git a/zig/kernels/hip/attention/prefill.hip b/zig/kernels/hip/attention/prefill.hip new file mode 100644 index 00000000000..87e39f57d46 --- /dev/null +++ b/zig/kernels/hip/attention/prefill.hip @@ -0,0 +1,278 @@ +// Prefill attention for long prompts: 64 query rows share a 64-key tile; dot2 products and online softmax in fp32. + +#include +#include +#include + +#include "decode/pages.hpp" + +namespace { + +constexpr int kRows = 64; // query rows a block +constexpr int kKeys = 64; // keys a tile +constexpr int kChunk = 64; // head dimensions a staged key or value chunk +constexpr int kThreads = 256; +static_assert(kKeys == kPageTokens, "a key tile is one page"); + +// A cache element type's pair for dot2, the rounding into it and the product. +template +struct Dot; + +template <> +struct Dot<__half> { + using elem = _Float16; + using pair = _Float16 __attribute__((ext_vector_type(2))); + static __device__ __forceinline__ float dot(pair a, pair b, float acc) { + return __builtin_amdgcn_fdot2(a, b, acc, false); + } +}; + +template <> +struct Dot { + using elem = __bf16; + using pair = __bf16 __attribute__((ext_vector_type(2))); + static __device__ __forceinline__ float dot(pair a, pair b, float acc) { +#if TF_DOT2_BF16 + return __builtin_amdgcn_fdot2_f32_bf16(a, b, acc, false); +#else + // RDNA2 has no bf16 dot2: its caches are fp16, this only keeps the kernel building + return fmaf(static_cast(a.y), static_cast(b.y), fmaf(static_cast(a.x), static_cast(b.x), acc)); +#endif + } +}; + +// A 16-byte LDS read as four pairs. +template +__device__ __forceinline__ void pairs4(const void* at, Pair out[4]) { + const uint4 w = *reinterpret_cast(at); + out[0] = __builtin_bit_cast(Pair, w.x); + out[1] = __builtin_bit_cast(Pair, w.y); + out[2] = __builtin_bit_cast(Pair, w.z); + out[3] = __builtin_bit_cast(Pair, w.w); +} + +// q rounds to the cache type once and stays in LDS; with PAGED, k and v are a layer's pools and a 64-key tile a page. +template +__device__ void fa_dot2(const float* __restrict__ q, const Cache* __restrict__ k, const Cache* __restrict__ v, + float* __restrict__ out, int qlen, int span, int heads, int kv_heads, int d, float scale, + int q_pos0, long long k_sb, long long k_sh, long long k_ss, long long v_sb, long long v_sh, + long long v_ss, const unsigned* table, int count) { + constexpr int kQChunks = 256 / 8; // 16-byte chunks a q row + constexpr int kKChunks = kChunk / 8; // a staged key row's + constexpr int kPLd = kRows + 4; // a key pair's probabilities, row-indexed + __shared__ uint4 sQ[kRows * kQChunks]; + __shared__ uint4 sKV[kKeys * kKChunks]; // a key chunk (key, 8 dims) or a value chunk (key pair, 4 dims) + using T = Dot; + using elem = typename T::elem; + using pair_t = typename T::pair; + __shared__ alignas(16) pair_t sH[kKeys / 2 * kPLd]; + __shared__ float sA[kRows], sL[kRows]; + + const int q0 = blockIdx.x * kRows; + const int head = blockIdx.y; + const int batch = blockIdx.z; + if (q0 >= qlen) return; + const int tid = threadIdx.x; + int q_hi = qlen - q0; + if (q_hi > kRows) q_hi = kRows; + int max_vis = q_pos0 + q0 + q_hi; + if (max_vis > span) max_vis = span; + const int kv = head / (heads / kv_heads); + const float* qrows = q + ((static_cast(batch) * heads + head) * qlen + q0) * d; + float* orows = out + ((static_cast(batch) * heads + head) * qlen + q0) * d; + const Cache* kbase = PAGED ? k : k + static_cast(batch) * k_sb + static_cast(kv) * k_sh; + const Cache* vbase = PAGED ? v : v + static_cast(batch) * v_sb + static_cast(kv) * v_sh; + const long long kstride = PAGED ? d : k_ss; + const long long vstride = PAGED ? d : v_ss; + const int chunks = d / 8; + + for (int e = tid; e < kRows * chunks; e += kThreads) { + const int row = e / chunks, c = e % chunks; + elem h[8]; +#pragma unroll + for (int m = 0; m < 8; ++m) + h[m] = static_cast(row < q_hi ? qrows[static_cast(row) * d + 8 * c + m] : 0.f); + sQ[row * kQChunks + (c ^ (row & 7))] = __builtin_bit_cast(uint4, h); + } + + // scores: rows sr + 16i against keys 4sk .. 4sk + 3; PV: rows pr .. pr + 3 at dims 4pc .. 4pc + 3 of each chunk + const int sr = tid / 16, sk = tid % 16; + const int pr = (tid / 16) * 4, pc = tid % 16; + float m_run[4], l_run[4]; +#pragma unroll + for (int i = 0; i < 4; ++i) m_run[i] = -INFINITY, l_run[i] = 0.f; + float o[4][16]; +#pragma unroll + for (int i = 0; i < 4; ++i) +#pragma unroll + for (int m = 0; m < 16; ++m) o[i][m] = 0.f; + + for (int k0 = 0; k0 < max_vis; k0 += kKeys) { + // the tile's first key row in the keys' and the values' storage + const Cache* ktile = PAGED ? kbase + page_row(table[k0 / kPageTokens], count, kv, 0, d) : kbase + static_cast(k0) * k_ss; + const Cache* vtile = PAGED ? vbase + page_row(table[k0 / kPageTokens], count, kv, 0, d) : vbase + static_cast(k0) * v_ss; + float acc[4][4]; +#pragma unroll + for (int i = 0; i < 4; ++i) +#pragma unroll + for (int j = 0; j < 4; ++j) acc[i][j] = 0.f; + for (int c0 = 0; c0 < chunks; c0 += kKChunks) { + uint4 staged[2]; +#pragma unroll + for (int t = 0; t < 2; ++t) { + const int e = tid + t * kThreads, key = e / kKChunks, c = e % kKChunks; + staged[t] = k0 + key < span + ? *reinterpret_cast(ktile + static_cast(key) * kstride + 8 * (c0 + c)) + : uint4{0, 0, 0, 0}; + } + __syncthreads(); +#pragma unroll + for (int t = 0; t < 2; ++t) { + const int e = tid + t * kThreads, key = e / kKChunks, c = e % kKChunks; + sKV[key * kKChunks + (c ^ ((key >> 2) & 7))] = staged[t]; + } + __syncthreads(); +#pragma unroll 2 + for (int c = 0; c < kKChunks; ++c) { + pair_t qv[4][4], kf[4][4]; +#pragma unroll + for (int i = 0; i < 4; ++i) { + const int row = sr + 16 * i; + pairs4(&sQ[row * kQChunks + ((c0 + c) ^ (row & 7))], qv[i]); + } +#pragma unroll + for (int j = 0; j < 4; ++j) { + const int key = 4 * sk + j; + pairs4(&sKV[key * kKChunks + (c ^ ((key >> 2) & 7))], kf[j]); + } +#pragma unroll + for (int i = 0; i < 4; ++i) +#pragma unroll + for (int j = 0; j < 4; ++j) +#pragma unroll + for (int m = 0; m < 4; ++m) acc[i][j] = T::dot(qv[i][m], kf[j][m], acc[i][j]); + } + } + // the online softmax in registers: a row's 64 keys sit on its 16 lanes +#pragma unroll + for (int i = 0; i < 4; ++i) { + const int row = sr + 16 * i; + int vis = q_pos0 + q0 + row + 1; + if (vis > span) vis = span; + float tile_max = -INFINITY; +#pragma unroll + for (int j = 0; j < 4; ++j) { + acc[i][j] = (row < q_hi && k0 + 4 * sk + j < vis) ? acc[i][j] * scale : -INFINITY; + tile_max = fmaxf(tile_max, acc[i][j]); + } +#pragma unroll + for (int lane = 8; lane > 0; lane >>= 1) tile_max = fmaxf(tile_max, __shfl_xor(tile_max, lane, 16)); + const float next_m = fmaxf(m_run[i], tile_max); + const float alpha = next_m == -INFINITY ? 1.f : expf(m_run[i] - next_m); + float p[4], sum = 0.f; +#pragma unroll + for (int j = 0; j < 4; ++j) { + p[j] = next_m == -INFINITY ? 0.f : expf(acc[i][j] - next_m); + sum += p[j]; + } +#pragma unroll + for (int lane = 8; lane > 0; lane >>= 1) sum += __shfl_xor(sum, lane, 16); + l_run[i] = alpha * l_run[i] + sum; + m_run[i] = next_m; + sH[(2 * sk) * kPLd + row] = pair_t{static_cast(p[0]), static_cast(p[1])}; + sH[(2 * sk + 1) * kPLd + row] = pair_t{static_cast(p[2]), static_cast(p[3])}; + if (sk == 0) sA[row] = alpha; + } +#pragma unroll + for (int at = 0; at < 256 / kChunk; ++at) { + if (at * kKChunks >= chunks) break; + const int c0 = at * kKChunks; + // a value chunk: key pair `pair`, dims 8g .. 8g + 7 interleaved as (key, key + 1) fp16 pairs + const int pair = tid / kKChunks, g = tid % kKChunks; + const int key = k0 + 2 * pair; + const uint4 a = key < span ? *reinterpret_cast(vtile + static_cast(2 * pair) * vstride + 8 * (c0 + g)) + : uint4{0, 0, 0, 0}; + const uint4 b = key + 1 < span + ? *reinterpret_cast(vtile + static_cast(2 * pair + 1) * vstride + 8 * (c0 + g)) + : uint4{0, 0, 0, 0}; + __syncthreads(); + const elem* ha = reinterpret_cast(&a); + const elem* hb = reinterpret_cast(&b); + pair_t lo[4], hi[4]; +#pragma unroll + for (int m = 0; m < 4; ++m) lo[m] = pair_t{ha[m], hb[m]}, hi[m] = pair_t{ha[4 + m], hb[4 + m]}; + sKV[pair * 16 + 2 * g] = __builtin_bit_cast(uint4, lo); + sKV[pair * 16 + 2 * g + 1] = __builtin_bit_cast(uint4, hi); + __syncthreads(); + float pv[4][4]; +#pragma unroll + for (int i = 0; i < 4; ++i) +#pragma unroll + for (int m = 0; m < 4; ++m) pv[i][m] = 0.f; +#pragma unroll 4 + for (int pp = 0; pp < kKeys / 2; ++pp) { + pair_t pr4[4], vv[4]; + pairs4(sH + pp * kPLd + pr, pr4); + pairs4(&sKV[pp * 16 + pc], vv); +#pragma unroll + for (int i = 0; i < 4; ++i) +#pragma unroll + for (int m = 0; m < 4; ++m) pv[i][m] = T::dot(pr4[i], vv[m], pv[i][m]); + } +#pragma unroll + for (int i = 0; i < 4; ++i) +#pragma unroll + for (int m = 0; m < 4; ++m) { + float& acc_o = o[i][4 * at + m]; + acc_o = fmaf(sA[pr + i], acc_o, pv[i][m]); + } + } + } + if (sk == 0) +#pragma unroll + for (int i = 0; i < 4; ++i) sL[sr + 16 * i] = l_run[i]; + __syncthreads(); +#pragma unroll + for (int i = 0; i < 4; ++i) { + const int row = pr + i; + if (row >= q_hi) continue; + const float inv = sL[row] == 0.f ? 0.f : 1.f / sL[row]; +#pragma unroll + for (int at = 0; at < 256 / kChunk; ++at) { + if (at * kKChunks >= chunks) break; +#pragma unroll + for (int m = 0; m < 4; ++m) + orows[static_cast(row) * d + 64 * at + 4 * pc + m] = o[i][4 * at + m] * inv; + } + } +} + +} // namespace + +extern "C" __global__ void __launch_bounds__(kThreads, 1) +tf_fa_wide_f16(const float* q, const __half* k, const __half* v, float* out, int qlen, int span, int heads, + int kv_heads, int d, float scale, int q_pos0, long long k_sb, long long k_sh, long long k_ss, + long long v_sb, long long v_sh, long long v_ss) { + fa_dot2<__half, false>(q, k, v, out, qlen, span, heads, kv_heads, d, scale, q_pos0, k_sb, k_sh, k_ss, v_sb, v_sh, v_ss, nullptr, 0); +} + +extern "C" __global__ void __launch_bounds__(kThreads, 1) +tf_fa_wide_bf16(const float* q, const hip_bfloat16* k, const hip_bfloat16* v, float* out, int qlen, int span, + int heads, int kv_heads, int d, float scale, int q_pos0, long long k_sb, long long k_sh, + long long k_ss, long long v_sb, long long v_sh, long long v_ss) { + fa_dot2(q, k, v, out, qlen, span, heads, kv_heads, d, scale, q_pos0, k_sb, k_sh, k_ss, v_sb, + v_sh, v_ss, nullptr, 0); +} + +// The same tile over a stream's pages: `k` and `v` are a layer's pools, `table` the stream's page ids. +extern "C" __global__ void __launch_bounds__(kThreads, 1) +tf_fa_paged_f16(const float* q, const __half* k, const __half* v, float* out, int qlen, int span, int heads, + int kv_heads, int d, float scale, int q_pos0, const unsigned* table, int count) { + fa_dot2<__half, true>(q, k, v, out, qlen, span, heads, kv_heads, d, scale, q_pos0, 0, 0, 0, 0, 0, 0, table, count); +} + +extern "C" __global__ void __launch_bounds__(kThreads, 1) +tf_fa_paged_bf16(const float* q, const hip_bfloat16* k, const hip_bfloat16* v, float* out, int qlen, int span, + int heads, int kv_heads, int d, float scale, int q_pos0, const unsigned* table, int count) { + fa_dot2(q, k, v, out, qlen, span, heads, kv_heads, d, scale, q_pos0, 0, 0, 0, 0, 0, 0, table, count); +} diff --git a/zig/kernels/hip/common/arch.hpp b/zig/kernels/hip/common/arch.hpp new file mode 100644 index 00000000000..5aeb14f5f39 --- /dev/null +++ b/zig/kernels/hip/common/arch.hpp @@ -0,0 +1,53 @@ +#pragma once + +// RDNA2 (dot2), RDNA3 / 3.5 (gfx11 WMMA), RDNA4 (gfx12 WMMA) from the build's TF_* cap macros; RDNA1 is refused. + +#if !defined(TF_WAVE) || !defined(TF_MATRIX) +#error "the caps macros come from the build" +#endif + +namespace tf { +namespace rocm { + +enum class Gen { rdna2, rdna3, rdna4 }; + +// Device code only: host dispatch reads TF_MATRIX from the build. +#if defined(__gfx1200__) || defined(__gfx1201__) || defined(__gfx12_generic__) +inline constexpr Gen kGen = Gen::rdna4; +inline constexpr bool kWmma = true; +#elif defined(__gfx1100__) || defined(__gfx1101__) || defined(__gfx1102__) || defined(__gfx1103__) \ + || defined(__gfx1150__) || defined(__gfx1151__) || defined(__gfx1152__) || defined(__gfx1153__) \ + || defined(__gfx11_generic__) +inline constexpr Gen kGen = Gen::rdna3; +inline constexpr bool kWmma = true; +#elif defined(__gfx1030__) || defined(__gfx1031__) || defined(__gfx1032__) || defined(__gfx1033__) \ + || defined(__gfx1034__) || defined(__gfx1035__) || defined(__gfx1036__) +inline constexpr Gen kGen = Gen::rdna2; +inline constexpr bool kWmma = false; +#elif defined(__gfx1010__) || defined(__gfx1011__) || defined(__gfx1012__) +static_assert(false, "RDNA1 (gfx101x) is not a TensorFold target"); +#else +inline constexpr Gen kGen = Gen::rdna2; +inline constexpr bool kWmma = false; +#endif + +} // namespace rocm + +// v_dot2_f32_bf16 (gfx11 and gfx12 device code): the BF16 dot2 tiles of the RDNA3 experts. +#if defined(__gfx1100__) || defined(__gfx1101__) || defined(__gfx1102__) || defined(__gfx1103__) \ + || defined(__gfx1150__) || defined(__gfx1151__) || defined(__gfx1152__) || defined(__gfx1153__) \ + || defined(__gfx11_generic__) || defined(__gfx1200__) || defined(__gfx1201__) || defined(__gfx12_generic__) +#define TF_DEVICE_BF16_DOT2 1 +#else +#define TF_DEVICE_BF16_DOT2 0 +#endif + +// gfx11 device code: v_wmma_f32_16x16x16_bf16 with its wave32 layouts (gfx12's differs). +#if defined(__gfx1100__) || defined(__gfx1101__) || defined(__gfx1102__) || defined(__gfx1103__) \ + || defined(__gfx1150__) || defined(__gfx1151__) || defined(__gfx1152__) || defined(__gfx1153__) \ + || defined(__gfx11_generic__) +#define TF_DEVICE_WMMA_GFX11 1 +#else +#define TF_DEVICE_WMMA_GFX11 0 +#endif +} // namespace tf diff --git a/zig/kernels/hip/common/dot2.hpp b/zig/kernels/hip/common/dot2.hpp new file mode 100644 index 00000000000..f84a80f8518 --- /dev/null +++ b/zig/kernels/hip/common/dot2.hpp @@ -0,0 +1,71 @@ +#pragma once + +// The Dot plug-ins of the tiles: the multiply-accumulate unit of an activation type and its operands. + +#include + +#include "common/arch.hpp" + +namespace tf { +namespace rocm { + +typedef __bf16 bf16x2 __attribute__((ext_vector_type(2))); + +// One dot2 whose x pair is lane I of the lane's quad (DPP quad_perm), as a pair of 32-bit words. +template +__device__ inline float dot_quad_shared(uint32_t x, uint32_t w, float acc) { + const uint32_t shared = __builtin_amdgcn_mov_dpp(static_cast(x), I * 0x55, 0xf, 0xf, false); + return T::dot(__builtin_bit_cast(typename T::pair, shared), __builtin_bit_cast(typename T::pair, w), acc); +} + +// FP16 v_dot2_f32_f16 (RDNA2 and gfx11 / gfx12). +struct DotF16 { + using elem = __half; + using pair = __half2; + // A pair of 1.0: dotted with x it gives the sum of x. + static constexpr uint32_t ones = 0x3c003c00u; + __device__ static elem zero() { return __float2half(0.f); } + __device__ static pair two(elem a, elem b) { return __halves2half2(a, b); } + __device__ static float lo(pair p) { return __low2float(p); } + __device__ static float hi(pair p) { return __high2float(p); } + __device__ static float dot(pair x, pair q, float acc) { return __builtin_amdgcn_fdot2(x, q, acc, false); } + // On RDNA2 the DPP form of v_dot2c_f32_f16 does it in one instruction at full rate (row_share would halve it). + template + __device__ static float quad(uint32_t x, uint32_t w, float acc) { +#if !TF_DOT2_BF16 + asm("v_dot2c_f32_f16_dpp %0, %1, %2 quad_perm:[%3,%3,%3,%3] row_mask:0xf bank_mask:0xf" + : "+v"(acc) + : "v"(x), "v"(w), "n"(I)); + return acc; +#else + return dot_quad_shared(x, w, acc); +#endif + } +}; + +// BF16 v_dot2_f32_bf16 (gfx11 / gfx12). +struct DotBF16 { + using elem = __bf16; + using pair = bf16x2; + static constexpr uint32_t ones = 0x3f803f80u; + __device__ static elem zero() { return static_cast<__bf16>(0.f); } + __device__ static pair two(elem a, elem b) { return pair{a, b}; } + __device__ static float lo(pair p) { return static_cast(p.x); } + __device__ static float hi(pair p) { return static_cast(p.y); } + __device__ static float dot(pair x, pair q, float acc) { +#if TF_DEVICE_BF16_DOT2 + return __builtin_amdgcn_fdot2_f32_bf16(x, q, acc, false); +#else + __builtin_trap(); + return acc; +#endif + } + // The BF16 dot2 has no DPP form: the x word is moved across the quad first. + template + __device__ static float quad(uint32_t x, uint32_t w, float acc) { + return dot_quad_shared(x, w, acc); + } +}; + +} // namespace rocm +} // namespace tf diff --git a/zig/kernels/hip/common/vec.hpp b/zig/kernels/hip/common/vec.hpp new file mode 100644 index 00000000000..6f24575cbdb --- /dev/null +++ b/zig/kernels/hip/common/vec.hpp @@ -0,0 +1,11 @@ +#pragma once + +// The 128-bit vector the tiles load code words and activation rows with. + +namespace tf { +namespace rocm { + +using u32x4 = unsigned __attribute__((ext_vector_type(4))); + +} // namespace rocm +} // namespace tf diff --git a/zig/kernels/hip/common/wmma.hpp b/zig/kernels/hip/common/wmma.hpp new file mode 100644 index 00000000000..663cd59e2c9 --- /dev/null +++ b/zig/kernels/hip/common/wmma.hpp @@ -0,0 +1,30 @@ +#pragma once + +// The matrix-core Dot of gfx11: v_wmma_f32_16x16x16_bf16 with its wave32 layouts (gfx12's differs), over BF16 operands. + +#include "common/dot2.hpp" +#include "common/vec.hpp" + +namespace tf { +namespace rocm { + +typedef __bf16 bf16x16 __attribute__((ext_vector_type(16))); +typedef unsigned u32x8 __attribute__((ext_vector_type(8))); +typedef float f32x8 __attribute__((ext_vector_type(8))); + +// The 16 BF16 of a row's 16 k as one fragment: two 16-byte words of the staged tile. +__device__ inline bf16x16 frag16(const uint32_t* p) { + const u32x4 lo = *reinterpret_cast(p); + const u32x4 hi = *reinterpret_cast(p + 4); + return __builtin_bit_cast(bf16x16, __builtin_shufflevector(lo, hi, 0, 1, 2, 3, 4, 5, 6, 7)); +} + +// The BF16 elements and sums of DotBF16, and the 16 x 16 x 16 product of two fragments added to an accumulator. +struct WmmaBF16 : DotBF16 { +#if TF_DEVICE_WMMA_GFX11 + __device__ static f32x8 mma(bf16x16 a, bf16x16 b, f32x8 c) { return __builtin_amdgcn_wmma_f32_16x16x16_bf16_w32(a, b, c); } +#endif +}; + +} // namespace rocm +} // namespace tf diff --git a/zig/kernels/hip/decode/decode.hip b/zig/kernels/hip/decode/decode.hip new file mode 100644 index 00000000000..4f8328fd445 --- /dev/null +++ b/zig/kernels/hip/decode/decode.hip @@ -0,0 +1,423 @@ +// Decode-step kernels for a few rows: the MoE router, a wave an expert, and residual tails; sums in the fastest order. + +// kind: 1 fp16, 2 bf16 (ops/act.hip's numbering). + +#include +#include + +#include + +#include "decode/plan.hpp" + +namespace { + +__device__ __forceinline__ float bf16_up(uint32_t bits) { return __uint_as_float(bits << 16); } + +// Four consecutive activations (8 bytes) widened. +template +__device__ __forceinline__ float4 widen4(uint2 v) { + if constexpr (KIND == 1) { + const __half2 a = __builtin_bit_cast(__half2, v.x); + const __half2 b = __builtin_bit_cast(__half2, v.y); + return make_float4(__low2float(a), __high2float(a), __low2float(b), __high2float(b)); + } else { + return make_float4(bf16_up(v.x & 0xffffu), bf16_up(v.x >> 16), bf16_up(v.y & 0xffffu), bf16_up(v.y >> 16)); + } +} + +constexpr int kRouterWaves = 4; +constexpr int kRouterSteps = 16; // float4 loads a lane keeps in flight +constexpr int kRouterRows = 16; + +// logits[r, e] = x[r] . rows[e], 16 rows a block, a wave an expert; d is a multiple of 4, weight rows 16-byte aligned. +template +__device__ void router_decode(const void* x, const float* rows, float* logits, int r, int d, int e) { + const int lane = threadIdx.x & 31; + const int expert = blockIdx.x * kRouterWaves + (threadIdx.x >> 5); + if (expert >= e) return; + // blockIdx.y picks a block of 16 rows: a row's sums are the same whichever block it is in + const int first = blockIdx.y * kRouterRows; + x = static_cast(x) + static_cast(first) * d; + logits += static_cast(first) * e; + r = r - first < kRouterRows ? r - first : kRouterRows; + const float* w = rows + static_cast(expert) * d; + float acc[kRouterRows]; +#pragma unroll + for (int k = 0; k < kRouterRows; ++k) acc[k] = 0.f; + for (int base = 0; base < d; base += kRouterSteps * 128) { + float4 wv[kRouterSteps]; +#pragma unroll + for (int s = 0; s < kRouterSteps; ++s) { + const int at = base + (lane + 32 * s) * 4; + wv[s] = at < d ? *reinterpret_cast(w + at) : make_float4(0.f, 0.f, 0.f, 0.f); + } +#pragma unroll + for (int k = 0; k < kRouterRows; ++k) { + if (k >= r) continue; + const uint16_t* xr = static_cast(x) + static_cast(k) * d; +#pragma unroll + for (int s = 0; s < kRouterSteps; ++s) { + const int at = base + (lane + 32 * s) * 4; + if (at >= d) continue; + const float4 xv = widen4(*reinterpret_cast(xr + at)); + acc[k] = fmaf(xv.x, wv[s].x, acc[k]); + acc[k] = fmaf(xv.y, wv[s].y, acc[k]); + acc[k] = fmaf(xv.z, wv[s].z, acc[k]); + acc[k] = fmaf(xv.w, wv[s].w, acc[k]); + } + } + } +#pragma unroll + for (int k = 0; k < kRouterRows; ++k) { + float v = acc[k]; +#pragma unroll + for (int mask = 16; mask > 0; mask >>= 1) v += __shfl_xor(v, mask, 32); + if (lane == 0 && k < r) logits[static_cast(k) * e + expert] = v; + } +} + + +__device__ __forceinline__ float load_kind(const void* p, int kind, long long i) { + return kind == 1 ? __half2float(static_cast(p)[i]) : bf16_up(static_cast(p)[i]); +} + +// A float rounded to the activation kind (fp16 or bf16, to nearest even) and widened again. +__device__ __forceinline__ float round_kind(float v, int kind) { + if (kind == 1) return __half2float(__float2half_rn(v)); + if (v != v) return v; + const uint32_t u = __float_as_uint(v); + return __uint_as_float(((u + (((u >> 16) & 1u) + 0x7fffu)) >> 16) << 16); +} + +__device__ __forceinline__ void store_kind(void* p, int kind, long long i, float v) { + if (kind == 1) { + static_cast<__half*>(p)[i] = __float2half_rn(v); + } else { + const uint32_t u = __float_as_uint(v); + static_cast(p)[i] = v != v ? 0x7fc0 : static_cast((u + (((u >> 16) & 1u) + 0x7fffu)) >> 16); + } +} + +constexpr int kTailThreads = 512; +constexpr int kTailWidth = 8192; + +// One row a block, one launch: x = round(x + t), t = y or the slot-ordered weighted sum; normed = rms(x) * weight. +__device__ void tail_body(void* x, const void* y, const float* wts, const float* weight, void* normed, int kind, + int slots, int width, float eps) { + __shared__ float row_v[kTailWidth]; + __shared__ float part[kTailThreads / 32]; + const int row = blockIdx.x; + const long long at = static_cast(row) * width; + float sum = 0.f; + for (int i = threadIdx.x; i < width; i += kTailThreads) { + float t; + if (slots > 0) { + float acc = 0.f; + for (int s = 0; s < slots; ++s) { + acc += static_cast(y)[(static_cast(row) * slots + s) * width + i] * + wts[row * slots + s]; + } + t = round_kind(acc, kind); + } else { + t = load_kind(y, kind, at + i); + } + const float v = round_kind(load_kind(x, kind, at + i) + t, kind); + store_kind(x, kind, at + i, v); + row_v[i] = v; + sum += v * v; + } +#pragma unroll + for (int mask = 16; mask > 0; mask >>= 1) sum += __shfl_xor(sum, mask, 32); + if ((threadIdx.x & 31) == 0) part[threadIdx.x >> 5] = sum; + __syncthreads(); + float total = 0.f; +#pragma unroll + for (int w = 0; w < kTailThreads / 32; ++w) total += part[w]; + const float inv = rsqrtf(total / static_cast(width) + eps); + for (int i = threadIdx.x; i < width; i += kTailThreads) { + float value = row_v[i] * inv; + if (weight != nullptr) value *= weight[i]; + store_kind(normed, kind, at + i, value); + } +} + +// Conv launch arguments: x (rows, channels), taps, state, snapshots; q, k (rows, kw), v (rows, vw) out; norm, gate. +struct ConvArgs { + const void* x; + int kind; + const float* weight; + float* state; + float* states; + float* qn; + float* kn; + float* v; + int channels, kernel, rows, kw, vw; + const float* qw; + const float* kw_w; + float eps; + int norm; + const void* ga; + const void* gb; + const float* a_log; + const float* dt_bias; + float* gate; + float* beta; + int gcount, heads; + // A round's plan (plan.count null: the launch's own rows and state): a grid row a slot, rows and state from it. + PlanArgs plan; + int layer; +}; + +// The conv for a window's rows split into q, k, v: taps in order, then silu; q, k heads rms-normed; gate and beta last. +__device__ void conv_split_body(const ConvArgs& launch) { + __shared__ float sq[128]; + __shared__ float inv_s; + ConvArgs c = launch; + float* samples = nullptr; + const int conv_blocks = (c.channels + 127) / 128; + if (launch.plan.count != nullptr) { + const int slot = blockIdx.y; + // the gates are one pass over every row of the round, from the first slot's blocks + if (blockIdx.x >= conv_blocks && slot != 0) return; + if (blockIdx.x < conv_blocks) { + const int rows = launch.plan.count[slot]; + if (rows == 0) return; + const long long row0 = launch.plan.first[slot]; + c.rows = rows; + c.state = reinterpret_cast(plan_desc(launch.plan, slot)[plan_first(launch.layer)]); + c.x = static_cast(launch.x) + row0 * c.channels * 2; + c.qn += row0 * c.kw; + c.kn += row0 * c.kw; + c.v += row0 * c.vw; + // a window of rows keeps its input rows and leaves the window as the round found it, for its keep + const bool replayed = rows > 1 && slot + 1 < static_cast(gridDim.y); + c.states = nullptr; + samples = replayed ? reinterpret_cast(launch.plan.snaps[2 * launch.layer]) + row0 * c.channels : nullptr; + } + } + if (blockIdx.x >= conv_blocks) { + const int i = (blockIdx.x - conv_blocks) * 128 + threadIdx.x; + if (c.ga == nullptr || i >= c.gcount) return; + const int h = i % c.heads; + c.beta[i] = 1.f / (1.f + expf(-load_kind(c.gb, c.kind, i))); + const float xg = load_kind(c.ga, c.kind, i) + c.dt_bias[h]; + const float soft = xg > 20.f ? xg : log1pf(expf(xg)); + c.gate[i] = expf(-expf(c.a_log[h]) * soft); + return; + } + const int channel = blockIdx.x * 128 + threadIdx.x; + const bool live = channel < c.channels; + const bool head = c.norm == 128 && static_cast(blockIdx.x) * 128 < 2 * c.kw; + const float* taps = c.weight + static_cast(live ? channel : 0) * c.kernel; + const int kept = c.kernel - 1; + float history[7]; + if (live) { + for (int tap = 0; tap < kept; ++tap) history[tap] = c.state[static_cast(tap) * c.channels + channel]; + } + for (int r = 0; r < c.rows; ++r) { + float y = 0.f; + float sample = 0.f; + if (live) { + float acc = 0.f; + for (int tap = 0; tap < kept; ++tap) acc += history[tap] * taps[tap]; + sample = load_kind(c.x, c.kind, static_cast(r) * c.channels + channel); + acc += sample * taps[kept]; + y = acc * (1.f / (1.f + expf(-acc))); + } + if (head) { + // the norm of the head's 128 values, then the scale by its weight + __syncthreads(); + sq[threadIdx.x] = y * y; + __syncthreads(); + if (threadIdx.x < 32) { + float sum = 0.f; + for (int j = 0; j < 4; ++j) sum += sq[threadIdx.x + 32 * j]; +#pragma unroll + for (int mask = 16; mask > 0; mask >>= 1) sum += __shfl_xor(sum, mask, 32); + if (threadIdx.x == 0) inv_s = rsqrtf(sum / 128.f + c.eps); + } + __syncthreads(); + const bool is_q = channel < c.kw; + y = y * inv_s * (is_q ? c.qw : c.kw_w)[threadIdx.x]; + } + if (live) { + if (channel < c.kw) { + c.qn[static_cast(r) * c.kw + channel] = y; + } else if (channel < 2 * c.kw) { + c.kn[static_cast(r) * c.kw + channel - c.kw] = y; + } else { + c.v[static_cast(r) * c.vw + channel - 2 * c.kw] = y; + } + for (int tap = 0; tap < kept - 1; ++tap) history[tap] = history[tap + 1]; + if (kept > 0) history[kept - 1] = sample; + if (samples != nullptr) samples[static_cast(r) * c.channels + channel] = sample; + if (c.states != nullptr) { + for (int tap = 0; tap < kept; ++tap) { + c.states[(static_cast(r) * kept + tap) * c.channels + channel] = history[tap]; + } + } + } + } + if (live && samples == nullptr) { + for (int tap = 0; tap < kept; ++tap) c.state[static_cast(tap) * c.channels + channel] = history[tap]; + } +} + +// rms over rows of `width` fp32 values a wave a row as rms_rows; blockIdx.y picks the first or second set of rows. +__device__ void + rms2_body(const float* x0, const float* w0, float* y0, const float* x1, const float* w1, float* y1, int rows, + int width, float eps) { + constexpr int kMost = 1024 / 32; + const float* x = blockIdx.y == 0 ? x0 : x1; + const float* weight = blockIdx.y == 0 ? w0 : w1; + float* y = blockIdx.y == 0 ? y0 : y1; + const int lane = threadIdx.x & 31; + const int row = blockIdx.x * 8 + (threadIdx.x >> 5); + if (row >= rows) return; + const long long at = static_cast(row) * width; + float v[kMost]; + float sum = 0.f; +#pragma unroll + for (int j = 0; j < kMost; ++j) { + const int i = lane + 32 * j; + v[j] = i < width ? x[at + i] : 0.f; + if (i < width) sum += v[j] * v[j]; + } +#pragma unroll + for (int mask = 16; mask > 0; mask >>= 1) sum += __shfl_xor(sum, mask, 32); + const float inv = rsqrtf(__shfl(sum, 0, 32) / static_cast(width) + eps); +#pragma unroll + for (int j = 0; j < kMost; ++j) { + const int i = lane + 32 * j; + if (i >= width) break; + float value = v[j] * inv; + if (weight != nullptr) value *= weight[i]; + y[at + i] = value; + } +} + +// The gated norm out = rms(y) * weight * round(silu(z)) in the kind, a wave a (row, head), no fp32 round trip between. +__device__ void + gnorm_out_body(const float* y, const float* weight, const void* z, void* out, int kind, int rows, int width, + float eps) { + constexpr int kMost = 1024 / 32; + const int lane = threadIdx.x & 31; + const int row = blockIdx.x * 8 + (threadIdx.x >> 5); + if (row >= rows) return; + const long long at = static_cast(row) * width; + float v[kMost]; + float sum = 0.f; +#pragma unroll + for (int j = 0; j < kMost; ++j) { + const int i = lane + 32 * j; + v[j] = i < width ? y[at + i] : 0.f; + if (i < width) sum += v[j] * v[j]; + } +#pragma unroll + for (int mask = 16; mask > 0; mask >>= 1) sum += __shfl_xor(sum, mask, 32); + const float inv = rsqrtf(__shfl(sum, 0, 32) / static_cast(width) + eps); +#pragma unroll + for (int j = 0; j < kMost; ++j) { + const int i = lane + 32 * j; + if (i >= width) break; + float value = v[j] * inv; + if (weight != nullptr) value *= weight[i]; + const float zv = load_kind(z, kind, at + i); + store_kind(out, kind, at + i, value * round_kind(zv / (1.f + expf(-zv)), kind)); + } +} + +constexpr int kSelectThreads = 256; +constexpr int kSelectMax = 1024; + +__device__ __forceinline__ float round_bf16_f(float v) { return round_kind(v, 2); } + +// act.hip's moe_select with picks by rank: expert i is in the top k when fewer than k beat it; `items` writes the plan. +__device__ void select_body(const float* logits, int* pick, float* wts, int* items, int* members, int capacity, + int experts, int top_k) { + __shared__ float v[kSelectMax]; + __shared__ float top_v[32]; + __shared__ int top_i[32]; + const int row = blockIdx.x; + const int slots = top_k + 1; + const float* l = logits + static_cast(row) * (experts + 1); + for (int i = threadIdx.x; i < experts; i += kSelectThreads) v[i] = l[i]; + __syncthreads(); + for (int i = threadIdx.x; i < experts; i += kSelectThreads) { + const float vi = v[i]; + int rank = 0; +#pragma unroll 16 + for (int j = 0; j < experts; ++j) { + const float vj = v[j]; + rank += (vj > vi) || (vj == vi && j < i); + } + if (rank < top_k) { + top_v[rank] = vi; + top_i[rank] = i; + } + } + __syncthreads(); + if (threadIdx.x == 0) { + const float top = top_v[0]; + float ex[32]; + float total = 0.f; + for (int k = 0; k < top_k; ++k) { + ex[k] = expf(top_v[k] - top); + total += ex[k]; + } + for (int k = 0; k < top_k; ++k) { + pick[row * slots + k] = top_i[k]; + wts[row * slots + k] = round_bf16_f(ex[k] / total); + } + const float gate = round_bf16_f(l[experts]); + pick[row * slots + top_k] = experts; + wts[row * slots + top_k] = round_bf16_f(1.f / (1.f + expf(-gate))); + } + if (items != nullptr) { + __syncthreads(); + for (int k = threadIdx.x; k < capacity; k += kSelectThreads) { + const bool real = k < slots; + items[3 * k] = real ? pick[k] : 0; + items[3 * k + 1] = real ? k : 0; + items[3 * k + 2] = real ? 1 : 0; + if (real) members[k] = k; + } + } +} + +} // namespace + +extern "C" __global__ void __launch_bounds__(32 * kRouterWaves) + tf_router_decode_f16(const void* x, const float* rows, float* logits, int r, int d, int e) { + router_decode<1>(x, rows, logits, r, d, e); +} + +extern "C" __global__ void __launch_bounds__(32 * kRouterWaves) + tf_router_decode_bf16(const void* x, const float* rows, float* logits, int r, int d, int e) { + router_decode<2>(x, rows, logits, r, d, e); +} + +extern "C" __global__ void __launch_bounds__(kTailThreads) + tf_tail(void* x, const void* y, const float* wts, const float* weight, void* normed, int kind, int slots, int width, + float eps) { + tail_body(x, y, wts, weight, normed, kind, slots, width, eps); +} + +extern "C" __global__ void __launch_bounds__(128) tf_conv_split(ConvArgs c) { conv_split_body(c); } + +extern "C" __global__ void __launch_bounds__(256) + tf_rms2(const float* x0, const float* w0, float* y0, const float* x1, const float* w1, float* y1, int rows, int width, + float eps) { + rms2_body(x0, w0, y0, x1, w1, y1, rows, width, eps); +} + +extern "C" __global__ void __launch_bounds__(256) + tf_gnorm_out(const float* y, const float* weight, const void* z, void* out, int kind, int rows, int width, float eps) { + gnorm_out_body(y, weight, z, out, kind, rows, width, eps); +} + +extern "C" __global__ void __launch_bounds__(kSelectThreads) + tf_select_decode(const float* logits, int* pick, float* wts, int* items, int* members, int capacity, int experts, + int top_k) { + select_body(logits, pick, wts, items, members, capacity, experts, top_k); +} diff --git a/zig/kernels/hip/decode/pages.hpp b/zig/kernels/hip/decode/pages.hpp new file mode 100644 index 00000000000..89070fa945a --- /dev/null +++ b/zig/kernels/hip/decode/pages.hpp @@ -0,0 +1,14 @@ +#pragma once + +// Paged KV: a pool of `count` 64-position pages a head, named by a stream's table; a head's pages sit side by side. +constexpr int kPageTokens = 64; + +// The element offset in a pool of `count` pages a head of head `h`, slot `slot` of page `page`. +__device__ __forceinline__ long long page_row(unsigned page, unsigned count, int h, int slot, int d) { + return ((static_cast(h) * count + page) * kPageTokens + slot) * d; +} + +// The element offset in a pool of head `h` at stream position `pos`. +__device__ __forceinline__ long long page_at(const unsigned* table, unsigned count, int h, int pos, int d) { + return page_row(table[pos / kPageTokens], count, h, pos % kPageTokens, d); +} diff --git a/zig/kernels/hip/decode/plan.hip b/zig/kernels/hip/decode/plan.hip new file mode 100644 index 00000000000..e2261447770 --- /dev/null +++ b/zig/kernels/hip/decode/plan.hip @@ -0,0 +1,219 @@ +// A lane round's attention walk, cache writes and keep, read from the round's plan on the device (plan.hpp). + +#include "ops/common.hpp" +#include "decode/plan.hpp" + +namespace { + +__device__ __forceinline__ float wave_sum(float x) { +#pragma unroll + for (int mask = 16; mask > 0; mask >>= 1) x += __shfl_xor(x, mask, 32); + return __shfl(x, 0, 32); +} + +// Row r's keys (already rotated, fp32) and values (the activation kind) into its slot's pages at its position. +__device__ void plan_kv_write_body(const float* keys, const void* values, int kind, int rows, int kv_heads, int d, + PlanArgs plan, int layer) { + const long long i = gid(); + if (i >= static_cast(rows) * kv_heads * d) return; + const int j = static_cast(i % d); + const int h = static_cast((i / d) % kv_heads); + const int r = static_cast(i / (static_cast(d) * kv_heads)); + const unsigned long long* desc = plan_desc(plan, plan.slot[r]); + const long long to = page_at(plan_pages(plan, desc), plan.pool, h, plan.pos[r], d) + j; + store(reinterpret_cast(desc[plan_first(layer)]), kind, to, keys[i]); + static_cast(reinterpret_cast(desc[plan_second(layer)]))[to] = static_cast(values)[i]; +} + +// Query heads a block takes together: they share a KV head, so its keys and values are read once for all of them. +constexpr int kMaxGroup = 16; + +// score_keys over a plan's rows: a warp scores a key for each of the block's heads (one KV head's), in its order. +template +__device__ void plan_score_body(const float* __restrict__ q, float* __restrict__ scores, int span, int heads, + int kv_heads, int d, float scale, PlanArgs plan, int layer) { + extern __shared__ float qs[]; // the block's query heads, group * d + const int batch = blockIdx.z; + const int group = heads / gridDim.y; + const int head0 = blockIdx.y * group; + const float* qrows = q + (static_cast(batch) * heads + head0) * d; + for (int i = threadIdx.x; i < group * d; i += blockDim.x) qs[i] = qrows[i]; + __syncthreads(); + const int visible = min(plan.pos[batch] + 1, span); + const int lane = threadIdx.x & 31; + const int key = blockIdx.x * (blockDim.x >> 5) + (threadIdx.x >> 5); + float kreg[8] = {}; + if (key < visible) { + const unsigned long long* desc = plan_desc(plan, plan.slot[batch]); + const void* keys = reinterpret_cast(desc[plan_first(layer)]); + const long long base = page_at(plan_pages(plan, desc), plan.pool, head0 / (heads / kv_heads), key, d); +#pragma unroll + for (int i = 0; i < 8; ++i) { + const int idx = lane + i * 32; + if (idx < d) kreg[i] = load(keys, KIND, base + idx); + } + } +#pragma unroll + for (int g = 0; g < kMaxGroup; ++g) { + if (g < group) { // the same for the whole block, so every lane reaches wave_sum + float partial = 0.f; + if (key < visible) { +#pragma unroll + for (int i = 0; i < 8; ++i) { + const int idx = lane + i * 32; + if (idx < d) partial += qs[g * d + idx] * kreg[i]; + } + } + const float dot = wave_sum(partial); + if (lane == 0 && key < span) { + const float score = key < visible ? dot * scale : -INFINITY; + scores[(static_cast(batch) * heads + head0 + g) * span + key] = score; + } + } + } +} + +// apply_values over a plan's rows: a 128-key tile of the block's heads, weights worked once a block, in its order. +template +__device__ void plan_apply_body(const float* __restrict__ scores, const float* __restrict__ stats, + float* __restrict__ partials, int span, int heads, int kv_heads, int d, + PlanArgs plan, int layer) { + __shared__ float weights[kMaxGroup * 128]; + const int batch = blockIdx.z; + const int visible = min(plan.pos[batch] + 1, span); + const int tile = blockIdx.x; + const int group = heads / gridDim.y; + const int head0 = blockIdx.y * group; + const long long first = static_cast(batch) * heads + head0; + const int lane = threadIdx.x; + const int key0 = tile * 128; + if (key0 >= visible) { // a tile past the keys in use adds zero + if (lane < d) { + for (int g = 0; g < group; ++g) partials[((first + g) * gridDim.x + tile) * d + lane] = 0.f; + } + return; + } + const int stop = min(key0 + 128, visible); + for (int i = threadIdx.x; i < group * 128; i += blockDim.x) { + const long long h = first + i / 128; + const int key = key0 + i % 128; + if (key < stop) weights[i] = expf(scores[h * span + key] - stats[h * 2]) / stats[h * 2 + 1]; + } + __syncthreads(); + if (lane >= d) return; + const unsigned long long* desc = plan_desc(plan, plan.slot[batch]); + const void* values = reinterpret_cast(desc[plan_second(layer)]); + const unsigned* table = plan_pages(plan, desc); + const int kv = head0 / (heads / kv_heads); + float acc[kMaxGroup] = {}; + // a page at a time: its table entry is read once, and the keys are summed in order + for (int key = key0; key < stop;) { + const int edge = min((key / kPageTokens + 1) * kPageTokens, stop); + const long long slot0 = page_row(table[key / kPageTokens], plan.pool, kv, 0, d) + lane; + for (; key < edge; ++key) { + const float value = load(values, KIND, slot0 + static_cast(key % kPageTokens) * d); +#pragma unroll + for (int g = 0; g < kMaxGroup; ++g) { + if (g < group) acc[g] += weights[g * 128 + key - key0] * value; + } + } + } +#pragma unroll + for (int g = 0; g < kMaxGroup; ++g) { + if (g < group) partials[((first + g) * gridDim.x + tile) * d + lane] = acc[g]; + } +} + +// The words of a row copied by a block row of threads, four at a time. +__device__ __forceinline__ void copy_words(unsigned int* to, const unsigned int* from, int words) { + const int stride = gridDim.x * blockDim.x; + for (int i = (blockIdx.x * blockDim.x + threadIdx.x) * 4; i < words; i += stride * 4) { + *reinterpret_cast(to + i) = *reinterpret_cast(from + i); + } +} + +} // namespace + +extern "C" { + +__global__ void __launch_bounds__(256) +tf_plan_kv_write(const float* keys, const void* values, int kind, int rows, int kv_heads, int d, PlanArgs plan, int layer) { + plan_kv_write_body(keys, values, kind, rows, kv_heads, d, plan, layer); +} + +__global__ void __launch_bounds__(128) +tf_plan_score_f16(const float* q, float* scores, int span, int heads, int kv_heads, int d, float scale, PlanArgs plan, int layer) { + plan_score_body<1>(q, scores, span, heads, kv_heads, d, scale, plan, layer); +} + +__global__ void __launch_bounds__(128) +tf_plan_score_bf16(const float* q, float* scores, int span, int heads, int kv_heads, int d, float scale, PlanArgs plan, int layer) { + plan_score_body<2>(q, scores, span, heads, kv_heads, d, scale, plan, layer); +} + +__global__ void __launch_bounds__(256) +tf_plan_apply_f16(const float* scores, const float* stats, float* partials, int span, int heads, int kv_heads, int d, PlanArgs plan, int layer) { + plan_apply_body<1>(scores, stats, partials, span, heads, kv_heads, d, plan, layer); +} + +__global__ void __launch_bounds__(256) +tf_plan_apply_bf16(const float* scores, const float* stats, float* partials, int span, int heads, int kv_heads, int d, PlanArgs plan, int layer) { + plan_apply_body<2>(scores, stats, partials, span, heads, kv_heads, d, plan, layer); +} + +// A prompt pass's rotated, rounded keys and values (16-bit) into positions pos0 .. pos0 + len of a stream's pages. +__global__ void __launch_bounds__(256) +tf_page_write(const uint16_t* src, uint16_t* pool, const unsigned* table, int len, int kv_heads, int d, long long s_head, + long long s_row, int pos0, int count) { + const long long i = gid(); + if (i >= static_cast(len) * kv_heads * d) return; + const int j = static_cast(i % d); + const int h = static_cast((i / d) % kv_heads); + const int r = static_cast(i / (static_cast(d) * kv_heads)); + pool[page_at(table, count, h, pos0 + r, d) + j] = src[h * s_head + r * s_row + j]; +} + +// The first `len` positions of a stream's pages as (kv_heads, len, d), the flat layout other attention kernels read. +__global__ void __launch_bounds__(256) +tf_page_gather(const uint16_t* pool, const unsigned* table, uint16_t* dst, int len, int kv_heads, int d, int count) { + const long long i = gid(); + if (i >= static_cast(len) * kv_heads * d) return; + const int j = static_cast(i % d); + const int r = static_cast((i / d) % len); + const int h = static_cast(i / (static_cast(d) * len)); + dst[i] = pool[page_at(table, count, h, r, d) + j]; +} + +// Row r of `dst` is `words` words from the address srcs[r]: a launch whose rows come from anywhere keeps its arguments. +__global__ void __launch_bounds__(256) tf_plan_gather(const unsigned long long* srcs, unsigned int* dst, int words) { + const unsigned int* from = reinterpret_cast(srcs[blockIdx.y]); + unsigned int* to = dst + static_cast(blockIdx.y) * words; + for (int i = blockIdx.x * blockDim.x + threadIdx.x; i < words; i += gridDim.x * blockDim.x) to[i] = from[i]; +} + +// Each slot's conv window and last final row after its first keep[slot] rows (negative: none); states: tf_gdn_replay. +__global__ void __launch_bounds__(256) +tf_plan_keep(PlanArgs plan, const int* keep, const unsigned int* hidden, int hidden_words, int channels, int taps, int layers) { + const int slot = blockIdx.z; + const int n = keep[slot]; + if (n < 0) return; + const unsigned long long* desc = plan_desc(plan, slot); + if (blockIdx.y == layers) { + const int row = plan.first[slot] + n - 1; + if (desc[1] != 0) copy_words(reinterpret_cast(desc[1]), hidden + static_cast(row) * hidden_words, hidden_words); + return; + } + const int layer = blockIdx.y; + if (plan.count[slot] <= 1 || plan.snaps[2 * layer] == 0) return; + float* window = reinterpret_cast(desc[plan_first(layer)]); + const float* samples = reinterpret_cast(plan.snaps[2 * layer]) + static_cast(plan.first[slot]) * channels; + // tap t takes position n - taps + t of the round's first window followed by its rows: ascending taps read ahead + for (int c = blockIdx.x * blockDim.x + threadIdx.x; c < channels; c += gridDim.x * blockDim.x) { + for (int t = 0; t < taps; ++t) { + const int at = n - taps + t; + window[static_cast(t) * channels + c] = at < 0 ? window[static_cast(taps + at) * channels + c] : samples[static_cast(at) * channels + c]; + } + } +} + +} // extern "C" diff --git a/zig/kernels/hip/decode/plan.hpp b/zig/kernels/hip/decode/plan.hpp new file mode 100644 index 00000000000..7e3af96b47b --- /dev/null +++ b/zig/kernels/hip/decode/plan.hpp @@ -0,0 +1,30 @@ +#pragma once + +#include + +#include "decode/pages.hpp" + +// A lane round's plan in device memory: no stream state is a launch argument, so one launch or graph serves any. +struct PlanArgs { + const int* pos; // per row: its position + const int* slot; // per row: its slot + const int* first; // per slot: its first row + const int* count; // per slot: its rows + const unsigned long long* desc; // per slot: the address of its descriptor + const unsigned long long* snaps; // per layer: the round's conv and DeltaNet snapshots, a row each + unsigned pages; // words of a descriptor before its page table + unsigned pool; // pages a head of a layer's pool holds +}; + +// Slot descriptor: [0] cached positions, [1] last kept final row, two cache addresses a layer, then the page table. +__device__ __forceinline__ const unsigned long long* plan_desc(const PlanArgs& p, int slot) { + return reinterpret_cast(p.desc[slot]); +} + +__device__ __forceinline__ int plan_first(int layer) { return 2 + 2 * layer; } + +__device__ __forceinline__ int plan_second(int layer) { return 3 + 2 * layer; } + +__device__ __forceinline__ const unsigned* plan_pages(const PlanArgs& p, const unsigned long long* desc) { + return reinterpret_cast(desc + p.pages); +} diff --git a/zig/kernels/hip/ops/act.hip b/zig/kernels/hip/ops/act.hip new file mode 100644 index 00000000000..0e21b6cef9b --- /dev/null +++ b/zig/kernels/hip/ops/act.hip @@ -0,0 +1,279 @@ + +#include +#include + +#include + +namespace tf { +namespace rocm { + +__device__ float warp_sum(float x) { +#pragma unroll + for (int mask = 16; mask > 0; mask >>= 1) x += __shfl_xor(x, mask, 32); + return __shfl(x, 0, 32); +} + +__device__ inline float widen(float v) { return v; } +__device__ inline float widen(__half v) { return __half2float(v); } +__device__ inline float widen(hip_bfloat16 v) { return static_cast(v); } +__device__ inline void narrow(float v, float* out) { *out = v; } +__device__ inline void narrow(float v, __half* out) { *out = __float2half_rn(v); } +__device__ inline void narrow(float v, hip_bfloat16* out) { *out = hip_bfloat16(v); } + +// fp32 sum of squares by one wave (lane l adds l, l + 32, ... then the xor tree), so bits do not depend on blockDim. +constexpr int kRmsThreads = 256; +constexpr int kRmsWidth = 8192; + +template +__global__ void __launch_bounds__(kRmsThreads) rms_kernel(const T* __restrict__ x, const float* __restrict__ weight, + T* __restrict__ y, int width, float eps) { + __shared__ float row_v[kRmsWidth]; + __shared__ float inv_s; + const int row = blockIdx.x; + const T* in = x + static_cast(row) * width; + for (int i = threadIdx.x; i < width; i += kRmsThreads) row_v[i] = widen(in[i]); + __syncthreads(); + if (threadIdx.x < 32) { + float sum = 0.f; + for (int i = threadIdx.x; i < width; i += 32) sum += row_v[i] * row_v[i]; + const float inv = rsqrtf(warp_sum(sum) / static_cast(width) + eps); + if (threadIdx.x == 0) inv_s = inv; + } + __syncthreads(); + const float inv = inv_s; + T* out = y + static_cast(row) * width; + for (int i = threadIdx.x; i < width; i += kRmsThreads) { + float value = row_v[i] * inv; + if (weight != nullptr) value *= weight[i]; + narrow(value, out + i); + } +} + +// Length 1. Taps run in order, then the state shifts toward the new sample. +extern "C" __global__ void tf_conv_decode(const float* __restrict__ x, const float* __restrict__ weight, + float* __restrict__ state, float* __restrict__ y, int channels, int kernel) { + int channel = blockIdx.x * blockDim.x + threadIdx.x; + int batch = blockIdx.y; + if (channel >= channels) return; + const float* row = weight + static_cast(channel) * kernel; + float history[7]; + int kept = kernel - 1; + float acc = 0.f; + for (int tap = 0; tap < kept; ++tap) { + history[tap] = state[(static_cast(batch) * kept + tap) * channels + channel]; + acc += history[tap] * row[tap]; + } + float sample = x[static_cast(batch) * channels + channel]; + acc += sample * row[kept]; + float gate = 1.f / (1.f + expf(-acc)); + y[(static_cast(batch) * channels) + channel] = acc * gate; + for (int tap = 0; tap < kept - 1; ++tap) { + state[(static_cast(batch) * kept + tap) * channels + channel] = history[tap + 1]; + } + if (kept > 0) state[(static_cast(batch) * kept + kept - 1) * channels + channel] = sample; +} + +// A window's rows in one launch: conv_decode's step for each row in turn, the state after each kept in ``states``. +extern "C" __global__ void tf_conv_rows(const float* __restrict__ x, const float* __restrict__ weight, + float* __restrict__ state, float* __restrict__ y, float* __restrict__ states, + int channels, int kernel, int rows) { + int channel = blockIdx.x * blockDim.x + threadIdx.x; + if (channel >= channels) return; + const float* row = weight + static_cast(channel) * kernel; + float history[7]; + int kept = kernel - 1; + for (int tap = 0; tap < kept; ++tap) history[tap] = state[static_cast(tap) * channels + channel]; + for (int r = 0; r < rows; ++r) { + float acc = 0.f; + for (int tap = 0; tap < kept; ++tap) acc += history[tap] * row[tap]; + float sample = x[static_cast(r) * channels + channel]; + acc += sample * row[kept]; + float gate = 1.f / (1.f + expf(-acc)); + y[static_cast(r) * channels + channel] = acc * gate; + for (int tap = 0; tap < kept - 1; ++tap) history[tap] = history[tap + 1]; + if (kept > 0) history[kept - 1] = sample; + if (states != nullptr) { + for (int tap = 0; tap < kept; ++tap) { + states[(static_cast(r) * kept + tap) * channels + channel] = history[tap]; + } + } + } + for (int tap = 0; tap < kept; ++tap) state[static_cast(tap) * channels + channel] = history[tap]; +} + +// ``per`` > 0: rows of a window, ``per`` rows to a position, row r at ``pos_dev[r / per]``. +extern "C" __global__ void tf_rope_decode(const float* __restrict__ x, float* __restrict__ y, int width, int rotary, + int pos, float theta, const int* __restrict__ pos_dev, int per) { + int row = blockIdx.x; + if (pos_dev != nullptr) pos = per > 0 ? pos_dev[row / per] : *pos_dev; + int lane = threadIdx.x; + const float* in = x + static_cast(row) * width; + float* out = y + static_cast(row) * width; + int half = rotary >> 1; + for (int i = lane; i < half; i += 32) { + float freq = 1.f / powf(theta, static_cast(i) / static_cast(half)); + float ang = static_cast(pos) * freq; + float c = cosf(ang); + float s = sinf(ang); + float x1 = in[i]; + float x2 = in[half + i]; + out[i] = x1 * c - x2 * s; + out[half + i] = x1 * s + x2 * c; + } + for (int i = rotary + lane; i < width; i += 32) out[i] = in[i]; +} + +template +__global__ void __launch_bounds__(256) moe_router_kernel(const T* __restrict__ x, const float* __restrict__ rows, + float* __restrict__ logits, int d, int e) { + const int lane = threadIdx.x & 31; + const int expert = blockIdx.x * 8 + (threadIdx.x >> 5); + const int row = blockIdx.y; + if (expert >= e) return; + const T* xr = x + static_cast(row) * d; + const float* w = rows + static_cast(expert) * d; + float acc = 0.f; + for (int i = lane; i < d; i += 32) acc = fmaf(widen(xr[i]), w[i], acc); + acc = warp_sum(acc); + if (lane == 0) logits[static_cast(row) * e + expert] = acc; +} + +constexpr int kSelectMax = 1024; + +__device__ inline float round_bf16(float v) { return static_cast(hip_bfloat16(v)); } + +extern "C" __global__ void __launch_bounds__(32) tf_moe_select(const float* __restrict__ logits, int* __restrict__ pick, + float* __restrict__ wts, int* __restrict__ items, + int* __restrict__ members, int capacity, int experts, + int top_k) { + __shared__ float v[kSelectMax]; + __shared__ float ex[32]; + const int lane = threadIdx.x; + const int row = blockIdx.x; + const int slots = top_k + 1; + const float* l = logits + static_cast(row) * (experts + 1); + for (int i = lane; i < experts; i += 32) v[i] = l[i]; + __syncthreads(); + float top = 0.f, total = 0.f; + for (int k = 0; k < top_k; ++k) { + float best = -INFINITY; + int idx = 0x7fffffff; + for (int i = lane; i < experts; i += 32) { + const float value = v[i]; + if (value > best || (value == best && i < idx)) { + best = value; + idx = i; + } + } +#pragma unroll + for (int mask = 16; mask > 0; mask >>= 1) { + const float other = __shfl_xor(best, mask, 32); + const int at = __shfl_xor(idx, mask, 32); + if (other > best || (other == best && at < idx)) { + best = other; + idx = at; + } + } + if (k == 0) top = best; + const float e = expf(best - top); + total += e; + if (lane == 0) { + pick[row * slots + k] = idx; + ex[k] = e; + v[idx] = -INFINITY; + } + __syncthreads(); + } + if (lane == 0) { + for (int k = 0; k < top_k; ++k) wts[row * slots + k] = round_bf16(ex[k] / total); + const float gate = round_bf16(l[experts]); + pick[row * slots + top_k] = experts; + wts[row * slots + top_k] = round_bf16(1.f / (1.f + expf(-gate))); + } + if (items != nullptr) { + __syncthreads(); + for (int k = lane; k < capacity; k += 32) { + const bool real = k < slots; + items[3 * k] = real ? pick[k] : 0; + items[3 * k + 1] = real ? k : 0; + items[3 * k + 2] = real ? 1 : 0; + if (real) members[k] = k; + } + } +} + +template +__global__ void moe_act_kernel(const float* __restrict__ both, T* __restrict__ out, int width, float limit, + long long total) { + const long long i = static_cast(blockIdx.x) * blockDim.x + threadIdx.x; + if (i >= total) return; + const long long p = i / width; + const int c = static_cast(i - p * width); + float g = both[p * 2 * width + c]; + float u = both[p * 2 * width + width + c]; + if (limit > 0.f) { + g = fminf(g, limit); + u = fminf(fmaxf(u, -limit), limit); + } + narrow(g / (1.f + expf(-g)) * u, out + i); +} + +template +__global__ void moe_combine_kernel(const float* __restrict__ y, const float* __restrict__ wts, T* __restrict__ out, + int slots, int d) { + const int row = blockIdx.y; + const int c = blockIdx.x * blockDim.x + threadIdx.x; + if (c >= d) return; + float acc = 0.f; + for (int s = 0; s < slots; ++s) { + acc += y[(static_cast(row) * slots + s) * d + c] * wts[row * slots + s]; + } + narrow(acc, out + static_cast(row) * d + c); +} + +template +__global__ void gdn_gate_kernel(const T* __restrict__ a, const T* __restrict__ b, const float* __restrict__ a_log, + const float* __restrict__ dt_bias, float* __restrict__ gate, float* __restrict__ beta, + int count, int heads) { + const int i = blockIdx.x * blockDim.x + threadIdx.x; + if (i >= count) return; + const int h = i % heads; + beta[i] = 1.f / (1.f + expf(-widen(b[i]))); + const float x = widen(a[i]) + dt_bias[h]; + const float soft = x > 20.f ? x : log1pf(expf(x)); + gate[i] = expf(-expf(a_log[h]) * soft); +} + +// The template kernels launches.zig resolves. +template __global__ void rms_kernel(const float* __restrict__ x, const float* __restrict__ weight, + float* __restrict__ y, int width, float eps); +template __global__ void rms_kernel<__half>(const __half* __restrict__ x, const float* __restrict__ weight, + __half* __restrict__ y, int width, float eps); +template __global__ void rms_kernel(const hip_bfloat16* __restrict__ x, const float* __restrict__ weight, + hip_bfloat16* __restrict__ y, int width, float eps); +template __global__ void moe_router_kernel<__half>(const __half* __restrict__ x, const float* __restrict__ rows, + float* __restrict__ logits, int d, int e); +template __global__ void moe_router_kernel(const hip_bfloat16* __restrict__ x, + const float* __restrict__ rows, float* __restrict__ logits, int d, int e); +template __global__ void moe_act_kernel<__half>(const float* __restrict__ both, __half* __restrict__ out, int width, + float limit, long long total); +template __global__ void moe_act_kernel(const float* __restrict__ both, hip_bfloat16* __restrict__ out, + int width, float limit, long long total); +template __global__ void moe_combine_kernel(const float* __restrict__ y, const float* __restrict__ wts, + float* __restrict__ out, int slots, int d); +template __global__ void moe_combine_kernel<__half>(const float* __restrict__ y, const float* __restrict__ wts, + __half* __restrict__ out, int slots, int d); +template __global__ void moe_combine_kernel(const float* __restrict__ y, const float* __restrict__ wts, + hip_bfloat16* __restrict__ out, int slots, int d); +template __global__ void gdn_gate_kernel(const float* __restrict__ a, const float* __restrict__ b, + const float* __restrict__ a_log, const float* __restrict__ dt_bias, float* __restrict__ gate, + float* __restrict__ beta, int count, int heads); +template __global__ void gdn_gate_kernel<__half>(const __half* __restrict__ a, const __half* __restrict__ b, + const float* __restrict__ a_log, const float* __restrict__ dt_bias, float* __restrict__ gate, + float* __restrict__ beta, int count, int heads); +template __global__ void gdn_gate_kernel(const hip_bfloat16* __restrict__ a, + const hip_bfloat16* __restrict__ b, const float* __restrict__ a_log, const float* __restrict__ dt_bias, + float* __restrict__ gate, float* __restrict__ beta, int count, int heads); + +} // namespace rocm +} // namespace tf diff --git a/zig/kernels/hip/ops/attention.hpp b/zig/kernels/hip/ops/attention.hpp new file mode 100644 index 00000000000..c97bcf67f5a --- /dev/null +++ b/zig/kernels/hip/ops/attention.hpp @@ -0,0 +1,48 @@ +#pragma once + +#include "common.hpp" + +// The gated attention's o input and the cache writes. + +namespace { + +// out[r, h * d + j] = att * sigmoid(gate) rounded to kind; att is (heads, len, d), or (len, heads, d) with rows_major. +extern "C" __global__ void tf_attn_gate(const float* att, const void* qg, void* out, int kind, int len, int heads, int d, + int rows_major) { + long long i = gid(); + if (i >= static_cast(len) * heads * d) return; + int j = static_cast(i % d); + int h = static_cast((i / d) % heads); + int r = static_cast(i / (static_cast(d) * heads)); + float a = rows_major ? att[i] : att[(static_cast(h) * len + r) * d + j]; + float g = load(qg, kind, (static_cast(r) * heads + h) * 2 * d + d + j); + store(out, kind, i, a * sigmoid(g)); +} + +// keys or values (len, kv_heads, d) of kind into the cache (kv_heads, total, d) at slot pos0. +extern "C" __global__ void tf_kv_write(const void* src, void* cache, int kind, int len, int kv_heads, int d, int total, + int pos0) { + long long i = gid(); + if (i >= static_cast(len) * kv_heads * d) return; + int j = static_cast(i % d); + int h = static_cast((i / d) % kv_heads); + int r = static_cast(i / (static_cast(d) * kv_heads)); + long long to = (static_cast(h) * total + pos0 + r) * d + j; + if (kind == 0) static_cast(cache)[to] = static_cast(src)[i]; + else static_cast(cache)[to] = static_cast(src)[i]; +} + +// kv_write with the first slot read from the device (`pos`, one int32), so a captured graph replays at any position. +extern "C" __global__ void tf_kv_write_at(const void* src, void* cache, int kind, int len, int kv_heads, int d, int total, + const int* pos) { + long long i = gid(); + if (i >= static_cast(len) * kv_heads * d) return; + int j = static_cast(i % d); + int h = static_cast((i / d) % kv_heads); + int r = static_cast(i / (static_cast(d) * kv_heads)); + long long to = (static_cast(h) * total + *pos + r) * d + j; + if (kind == 0) static_cast(cache)[to] = static_cast(src)[i]; + else static_cast(cache)[to] = static_cast(src)[i]; +} + +} // namespace diff --git a/zig/kernels/hip/ops/common.hpp b/zig/kernels/hip/ops/common.hpp new file mode 100644 index 00000000000..980e5b5645c --- /dev/null +++ b/zig/kernels/hip/ops/common.hpp @@ -0,0 +1,46 @@ +#pragma once + +// The torch ops between kernels, bit for bit: round where torch rounds, no contraction; kind 0 fp32, 1 fp16, 2 bf16. + +#include +#include +#include + +namespace { + +__device__ __forceinline__ float bf16_to_float(uint16_t h) { return __uint_as_float(static_cast(h) << 16); } + +// c10::BFloat16's round to nearest even, NaN to 0x7fc0. +__device__ __forceinline__ uint16_t float_to_bf16(float f) { + if (f != f) return 0x7fc0; + uint32_t u = __float_as_uint(f); + uint32_t bias = ((u >> 16) & 1u) + 0x7fffu; + return static_cast((u + bias) >> 16); +} + +__device__ __forceinline__ float load(const void* p, int kind, long long i) { + if (kind == 0) return static_cast(p)[i]; + if (kind == 1) return __half2float(static_cast(p)[i]); + return bf16_to_float(static_cast(p)[i]); +} + +__device__ __forceinline__ void store(void* p, int kind, long long i, float v) { + if (kind == 0) static_cast(p)[i] = v; + else if (kind == 1) static_cast<__half*>(p)[i] = __float2half_rn(v); + else static_cast(p)[i] = float_to_bf16(v); +} + +// A value rounded to `kind` and widened again: what torch holds after an op that returns that dtype. +__device__ __forceinline__ float rounded(float v, int kind) { + if (kind == 1) return __half2float(__float2half_rn(v)); + if (kind == 2) return bf16_to_float(float_to_bf16(v)); + return v; +} + +// torch's silu and sigmoid on an fp32 operand: x / (1 + exp(-x)) and 1 / (1 + exp(-x)). +__device__ __forceinline__ float silu(float x) { return x / (1.0f + expf(-x)); } +__device__ __forceinline__ float sigmoid(float x) { return 1.0f / (1.0f + expf(-x)); } + +__device__ __forceinline__ long long gid() { return static_cast(blockIdx.x) * blockDim.x + threadIdx.x; } + +} // namespace diff --git a/zig/kernels/hip/ops/draw.hpp b/zig/kernels/hip/ops/draw.hpp new file mode 100644 index 00000000000..def5b8fba4e --- /dev/null +++ b/zig/kernels/hip/ops/draw.hpp @@ -0,0 +1,136 @@ +#pragma once + +#include "common.hpp" + +// Argmax and top-k of logits rows. + +namespace { + +constexpr int kThreads = 1024; +constexpr int kWaves = kThreads / 32; + +__device__ __forceinline__ float widen(uint16_t bits, int kind) { + if (kind == 1) return __half2float(__ushort_as_half(bits)); + return __uint_as_float(static_cast(bits) << 16); +} + +// torch's argmax order: a NaN beats every value, then the larger value, then the lower index. +__device__ __forceinline__ bool better(float a, int ia, float b, int ib) { + bool na = a != a, nb = b != b; + if (na || nb) return na && (!nb || ia < ib); + return a > b || (a == b && ia < ib); +} + +extern "C" __global__ void tf_argmax(const uint16_t* logits, int kind, int n, int* out) { + const uint16_t* row = logits + static_cast(blockIdx.x) * n; + float top = 0.0f; + int at = -1; + for (int i = threadIdx.x; i < n; i += kThreads) { + float v = widen(row[i], kind); + if (at < 0 || better(v, i, top, at)) { + top = v; + at = i; + } + } + __shared__ float sv[kThreads]; + __shared__ int si[kThreads]; + sv[threadIdx.x] = top; + si[threadIdx.x] = at; + __syncthreads(); + for (int stride = kThreads / 2; stride > 0; stride >>= 1) { + if (threadIdx.x < stride) { + int j = threadIdx.x + stride; + if (si[j] >= 0 && (si[threadIdx.x] < 0 || better(sv[j], si[j], sv[threadIdx.x], si[threadIdx.x]))) { + sv[threadIdx.x] = sv[j]; + si[threadIdx.x] = si[j]; + } + } + __syncthreads(); + } + if (threadIdx.x == 0) out[blockIdx.x] = si[0]; +} + +// A monotone 16-bit key of a value's bits (-0 and +0 share one), so equal keys are equal values. +__device__ __forceinline__ uint32_t order_key(uint16_t bits) { + if (bits == 0x8000) bits = 0; + return (bits & 0x8000) ? (~bits & 0xffffu) : (bits | 0x8000u); +} + +// Row r's ks[r] largest by (value desc, id asc): two histograms of the k-th key, then one ordered compaction. +extern "C" __global__ void tf_topk(const uint16_t* logits, int n, const int* ks, int stride, int* ids, uint16_t* values) { + const int r = blockIdx.x, k = ks[r]; + if (k <= 0) return; + const uint16_t* row = logits + static_cast(r) * n; + __shared__ int hist[256]; + __shared__ int pick[4]; // high byte, low byte, count above, count of the k-th key to take + __shared__ int wave_gt[kWaves], wave_eq[kWaves]; + for (int i = threadIdx.x; i < 256; i += kThreads) hist[i] = 0; + __syncthreads(); + for (int i = threadIdx.x; i < n; i += kThreads) atomicAdd(&hist[order_key(row[i]) >> 8], 1); + __syncthreads(); + if (threadIdx.x == 0) { + int above = 0, b = 255; + for (; b > 0 && above + hist[b] < k; --b) above += hist[b]; + pick[0] = b; + pick[2] = above; + } + __syncthreads(); + for (int i = threadIdx.x; i < 256; i += kThreads) hist[i] = 0; + __syncthreads(); + const uint32_t high = pick[0]; + for (int i = threadIdx.x; i < n; i += kThreads) { + uint32_t key = order_key(row[i]); + if ((key >> 8) == high) atomicAdd(&hist[key & 255u], 1); + } + __syncthreads(); + if (threadIdx.x == 0) { + int above = pick[2], b = 255; + for (; b > 0 && above + hist[b] < k; --b) above += hist[b]; + pick[1] = b; + pick[2] = above; // the keys above the k-th + pick[3] = k - above; // how many of the k-th's to take, lowest ids first + } + __syncthreads(); + const uint32_t kth = (high << 8) | static_cast(pick[1]); + const int above = pick[2], take = pick[3]; + int seen_gt = 0, seen_eq = 0; + const int lane = threadIdx.x & 31, wave = threadIdx.x >> 5; + for (int base = 0; base < n; base += kThreads) { + int i = base + threadIdx.x; + uint16_t bits = i < n ? row[i] : 0; + uint32_t key = order_key(bits); + bool gt = i < n && key > kth, eq = i < n && key == kth; + unsigned long long mg = __ballot(gt), me = __ballot(eq); + unsigned long long below = (1ull << lane) - 1; + if (lane == 0) { + wave_gt[wave] = __popcll(mg); + wave_eq[wave] = __popcll(me); + } + __syncthreads(); + int gt_before = seen_gt, eq_before = seen_eq; + for (int w = 0; w < wave; ++w) { + gt_before += wave_gt[w]; + eq_before += wave_eq[w]; + } + if (gt) { + int slot = gt_before + __popcll(mg & below); + ids[r * stride + slot] = i; + values[r * stride + slot] = bits; + } + if (eq) { + int rank = eq_before + __popcll(me & below); + if (rank < take) { + ids[r * stride + above + rank] = i; + values[r * stride + above + rank] = bits; + } + } + for (int w = 0; w < kWaves; ++w) { + seen_gt += wave_gt[w]; + seen_eq += wave_eq[w]; + } + __syncthreads(); + if (seen_eq >= take && seen_gt >= above) break; + } +} + +} // namespace diff --git a/zig/kernels/hip/ops/elementwise.hpp b/zig/kernels/hip/ops/elementwise.hpp new file mode 100644 index 00000000000..0b1d5bb7aed --- /dev/null +++ b/zig/kernels/hip/ops/elementwise.hpp @@ -0,0 +1,81 @@ +#pragma once + +#include "common.hpp" + +// Embedding rows, casts, sums, column copies and the draft projection. + +namespace { + +// An MLX code at index i of a packed row, including one that crosses two words (qwen_math._codes). +__device__ __forceinline__ uint32_t code_at(const uint32_t* row, int words, int bits, long long i) { + long long bit = i * bits; + int word = static_cast(bit / 32), shift = static_cast(bit % 32); + uint64_t low = row[word]; + uint64_t high = (shift + bits > 32 && word + 1 < words) ? row[word + 1] : 0; + uint64_t value = (low >> shift) | (high << ((32 - shift) & 31)); + return static_cast(value & ((1u << bits) - 1u)); +} + +extern "C" __global__ void tf_embed_rows(const uint32_t* words, const void* scale, const void* bias, int scale_kind, + const int* ids, int n, int bits, int group, int k, void* out, int out_kind) { + long long i = gid(); + if (i >= static_cast(n) * k) return; + int r = static_cast(i / k), c = static_cast(i % k); + long long id = ids[r]; + int words_row = k * bits / 32, groups = k / group; + float code = static_cast(code_at(words + id * words_row, words_row, bits, c)); + float s = load(scale, scale_kind, id * groups + c / group); + float b = load(bias, scale_kind, id * groups + c / group); + float y = code * s; + y = y + b; + store(out, out_kind, i, y); +} + +// The float gather: rows of an fp32 table (an embedding kept unquantized), written in the activation type. +extern "C" __global__ void tf_embed_dense(const float* table, const int* ids, int n, int k, void* out, int out_kind) { + long long i = gid(); + if (i >= static_cast(n) * k) return; + int r = static_cast(i / k), c = static_cast(i % k); + store(out, out_kind, i, table[static_cast(ids[r]) * k + c]); +} + +extern "C" __global__ void tf_cast(const void* src, int skind, void* dst, int dkind, long long n) { + long long i = gid(); + if (i < n) store(dst, dkind, i, load(src, skind, i)); +} + +extern "C" __global__ void tf_silu_mul(const void* gate, const void* up, void* out, int kind, long long n) { + long long i = gid(); + if (i >= n) return; + float s = rounded(silu(load(gate, kind, i)), kind); + store(out, kind, i, s * load(up, kind, i)); +} + +extern "C" __global__ void tf_add(const void* x, const void* y, void* out, int kind, long long n) { + long long i = gid(); + if (i < n) store(out, kind, i, load(x, kind, i) + load(y, kind, i)); +} + +// rows of `cols` values from a source with row stride `stride` at column `offset`, kept in kind. +extern "C" __global__ void tf_copy_cols(const void* src, long long stride, int offset, void* dst, int kind, int rows, + int cols) { + long long i = gid(); + if (i >= static_cast(rows) * cols) return; + long long r = i / cols; + int c = static_cast(i % cols); + long long from = r * stride + offset + c; + if (kind == 0) static_cast(dst)[i] = static_cast(src)[from]; + else static_cast(dst)[i] = static_cast(src)[from]; +} + +// y[r, n] = x[r, :] . w[n, :] over fp32 weights (MTP fc), a wave a value; drafts only, so the sum order is free. +extern "C" __global__ void tf_dense_rows(const void* x, int kind, const float* w, void* out, int rows, int n, int k) { + int col = blockIdx.x, r = blockIdx.y; + if (col >= n || r >= rows) return; + float acc = 0.0f; + for (int i = threadIdx.x; i < k; i += 32) acc += load(x, kind, static_cast(r) * k + i) * w[static_cast(col) * k + i]; + for (int off = 16; off > 0; off >>= 1) acc += __shfl_xor(acc, off, 32); + if (threadIdx.x == 0) store(out, kind, static_cast(r) * n + col, acc); +} + +} // namespace diff --git a/zig/kernels/hip/ops/linear.hpp b/zig/kernels/hip/ops/linear.hpp new file mode 100644 index 00000000000..e77529f1677 --- /dev/null +++ b/zig/kernels/hip/ops/linear.hpp @@ -0,0 +1,64 @@ +#pragma once + +#include "common.hpp" + +// The linear attention's prefill: conv, gate and gated norm. + +namespace { + +// Conv prefill: window [state | x], taps summed in order, then silu; row block 0 writes new_state, never `state`. +constexpr int kConvRows = 16; // rows a conv_prefill thread slides over +constexpr int kConvTaps = 8; // most taps it holds + +extern "C" __global__ void tf_conv_prefill(const void* x, int kind, const float* weight, const float* state, float* out, + float* new_state, int len, int channels, int kernel) { + // a thread one channel over kConvRows rows, the window sliding in registers (each input read once) + const int c = blockIdx.x * blockDim.x + threadIdx.x; + if (c >= channels) return; + const int r0 = blockIdx.y * kConvRows; + const int kept = kernel - 1; + auto window = [&](int t) -> float { + if (t < kept) return state ? state[static_cast(t) * channels + c] : 0.0f; + return load(x, kind, static_cast(t - kept) * channels + c); + }; + if (blockIdx.y == 0) + for (int t = 0; t < kept; ++t) new_state[static_cast(t) * channels + c] = window(len + t); + float w[kConvTaps], win[kConvTaps]; + for (int tap = 0; tap < kernel; ++tap) w[tap] = weight[static_cast(c) * kernel + tap]; + for (int tap = 0; tap + 1 < kernel; ++tap) win[tap] = window(r0 + tap); + const int r1 = r0 + kConvRows < len ? r0 + kConvRows : len; + for (int r = r0; r < r1; ++r) { + win[kernel - 1] = window(r + kernel - 1); + float acc = 0.0f; + for (int tap = 0; tap < kernel; ++tap) { + float p = win[tap] * w[tap]; + acc = acc + p; + } + out[static_cast(r) * channels + c] = silu(acc); + for (int tap = 0; tap + 1 < kernel; ++tap) win[tap] = win[tap + 1]; + } +} + +// _gate_beta: beta = sigmoid(b), gate = exp(-exp(a_log) * softplus(a + dt_bias)) with torch's softplus. +extern "C" __global__ void tf_gdn_gate_prefill(const void* a, const void* b, int kind, const float* a_log, + const float* dt_bias, float* gate, float* beta, int count, int heads) { + long long i = gid(); + if (i >= static_cast(count) * heads) return; + int h = static_cast(i % heads); + beta[i] = sigmoid(load(b, kind, i)); + float x = load(a, kind, i) + dt_bias[h]; + float xb = x * 1.0f; + float sp = xb > 20.0f ? x : log1pf(expf(xb)) / 1.0f; + float e = -expf(a_log[h]); + gate[i] = expf(e * sp); +} + +// out = y * silu(z) widened, rounded to kind: the linear-attention output before its projection. +extern "C" __global__ void tf_gnorm_silu(const float* y, const void* z, void* out, int kind, long long n) { + long long i = gid(); + if (i >= n) return; + float s = rounded(silu(load(z, kind, i)), kind); + store(out, kind, i, y[i] * s); +} + +} // namespace diff --git a/zig/kernels/hip/ops/moe.hpp b/zig/kernels/hip/ops/moe.hpp new file mode 100644 index 00000000000..f12329e903a --- /dev/null +++ b/zig/kernels/hip/ops/moe.hpp @@ -0,0 +1,217 @@ +#pragma once + +#include "common.hpp" + +// The MoE plan and the router's logits. + +namespace { + +// Stable-sorts the pairs by expert into members and cuts items of at most `tile` pairs; one block, counted per segment. +extern "C" __global__ void tf_moe_route(const int* picks, int pairs, int experts, int tile, int* members, int* items, + int capacity) { + extern __shared__ int shared[]; + int* counts = shared; + int* starts = shared + experts; + int* ends = shared + 2 * experts; + unsigned short* seg = reinterpret_cast(shared + 3 * experts); + const int segs = experts <= 256 ? 64 : 16; + const int span = (pairs + segs - 1) / segs; + const int t = threadIdx.x; + for (int i = t; i < segs * experts; i += blockDim.x) seg[i] = 0; + __syncthreads(); + if (t < segs) { + for (int p = t * span; p < pairs && p < (t + 1) * span; ++p) seg[t * experts + picks[p]] += 1; + } + __syncthreads(); + // an expert's total and each segment's first place for it (still relative to the expert's start) + for (int e = t; e < experts; e += blockDim.x) { + int run = 0; + for (int g = 0; g < segs; ++g) { + int c = seg[g * experts + e]; + seg[g * experts + e] = static_cast(run); + run += c; + } + counts[e] = run; + } + __syncthreads(); + if (t == 0) { + int start = 0, end = 0; + for (int e = 0; e < experts; ++e) { + starts[e] = start; + start += counts[e]; + end += (counts[e] + tile - 1) / tile; + ends[e] = end; + } + } + __syncthreads(); + if (t < segs) { + for (int p = t * span; p < pairs && p < (t + 1) * span; ++p) { + int e = picks[p]; + members[starts[e] + seg[t * experts + e]] = p; + seg[t * experts + e] += 1; + } + } + for (int slot = t; slot < capacity; slot += blockDim.x) { + int lo = 0, hi = experts; + while (lo < hi) { // searchsorted(ends, slot, right=True) + int mid = (lo + hi) / 2; + if (ends[mid] <= slot) lo = mid + 1; + else hi = mid; + } + int e = lo < experts - 1 ? lo : experts - 1; + int reps = (counts[e] + tile - 1) / tile; + int within = slot - (ends[e] - reps); + int count = counts[e] - within * tile; + items[slot * 3] = e; + items[slot * 3 + 1] = starts[e] + within * tile; + items[slot * 3 + 2] = count < 0 ? 0 : (count > tile ? tile : count); + } +} + +// moe_router_kernel's logits with a wave's expert row read once for 8 token rows; each logit keeps its bits. +__device__ __forceinline__ float router_sum(float x) { +#pragma unroll + for (int mask = 16; mask > 0; mask >>= 1) x += __shfl_xor(x, mask, 32); + return __shfl(x, 0, 32); +} + +template +__device__ void router_rows(const void* x, const float* rows, float* logits, int r, int d, int e) { + constexpr int kChunk = 1024; + __shared__ float xs[8][kChunk]; + const int lane = threadIdx.x & 31; + const int expert = blockIdx.x * 8 + (threadIdx.x >> 5); + const int row0 = blockIdx.y * 8; + const float* w = rows + static_cast(expert < e ? expert : 0) * d; + float acc[8]; +#pragma unroll + for (int k = 0; k < 8; ++k) acc[k] = 0.f; + for (int base = 0; base < d; base += kChunk) { + const int n = d - base < kChunk ? d - base : kChunk; + __syncthreads(); + for (int q = threadIdx.x; q < 8 * kChunk; q += blockDim.x) { + const int k = q / kChunk, i = q % kChunk; + xs[k][i] = (row0 + k < r && i < n) ? load(x, KIND, static_cast(row0 + k) * d + base + i) : 0.f; + } + __syncthreads(); + // lane l keeps adding i = l, l + 32, ... in order across the chunks + for (int i = lane; i < n; i += 32) { + const float wv = w[base + i]; +#pragma unroll + for (int k = 0; k < 8; ++k) acc[k] = fmaf(xs[k][i], wv, acc[k]); + } + } + if (expert >= e) return; +#pragma unroll + for (int k = 0; k < 8; ++k) { + const float sum = router_sum(acc[k]); + if (lane == 0 && row0 + k < r) logits[static_cast(row0 + k) * e + expert] = sum; + } +} + +// The router's logits for many rows: a 64 x 64 tile of (row, expert) a block, 4 x 4 a thread, in fp32. +template +__device__ void router_tile(const void* x, const float* rows, float* logits, int r, int d, int e) { + constexpr int kTile = 64, kStep = 32, kLd = kTile + 4; + __shared__ alignas(16) float xs[kStep][kLd]; + __shared__ alignas(16) float ws[kStep][kLd]; + const int row0 = blockIdx.y * kTile, expert0 = blockIdx.x * kTile; + const int ty = threadIdx.x / 16, tx = threadIdx.x % 16; + // the staging: activation row ar at steps ak .. ak + 7, router rows wr and wr + 32 at steps wk .. wk + 3 + const int ar = threadIdx.x / 4, ak = (threadIdx.x % 4) * 8; + const int wr = threadIdx.x / 8, wk = (threadIdx.x % 8) * 4; + const uint16_t* xh = static_cast(x); + float acc[4][4] = {}; + for (int base = 0; base < d; base += kStep) { + uint4 xv = {0, 0, 0, 0}; + if (row0 + ar < r) xv = *reinterpret_cast(xh + static_cast(row0 + ar) * d + base + ak); + float4 w0 = {0, 0, 0, 0}, w1 = {0, 0, 0, 0}; + if (expert0 + wr < e) w0 = *reinterpret_cast(rows + static_cast(expert0 + wr) * d + base + wk); + if (expert0 + wr + 32 < e) + w1 = *reinterpret_cast(rows + static_cast(expert0 + wr + 32) * d + base + wk); + __syncthreads(); + const uint16_t* h = reinterpret_cast(&xv); +#pragma unroll + for (int j = 0; j < 8; ++j) xs[ak + j][ar] = KIND == 1 ? __half2float(__ushort_as_half(h[j])) : bf16_to_float(h[j]); + const float a0[4] = {w0.x, w0.y, w0.z, w0.w}, a1[4] = {w1.x, w1.y, w1.z, w1.w}; +#pragma unroll + for (int j = 0; j < 4; ++j) ws[wk + j][wr] = a0[j], ws[wk + j][wr + 32] = a1[j]; + __syncthreads(); +#pragma unroll + for (int i = 0; i < kStep; ++i) { + const float4 a = *reinterpret_cast(&xs[i][4 * ty]); + const float4 b = *reinterpret_cast(&ws[i][4 * tx]); + const float av[4] = {a.x, a.y, a.z, a.w}, bv[4] = {b.x, b.y, b.z, b.w}; +#pragma unroll + for (int u = 0; u < 4; ++u) +#pragma unroll + for (int w = 0; w < 4; ++w) acc[u][w] = fmaf(av[u], bv[w], acc[u][w]); + } + } +#pragma unroll + for (int u = 0; u < 4; ++u) { + const int row = row0 + 4 * ty + u; + if (row >= r) continue; +#pragma unroll + for (int w = 0; w < 4; ++w) { + const int expert = expert0 + 4 * tx + w; + if (expert < e) logits[static_cast(row) * e + expert] = acc[u][w]; + } + } +} + +// router_tile's logits for up to 32 rows: a wave an expert, a lane a row, each logit one in-order fmaf chain. +template +__device__ void router_small(const void* x, const float* rows, float* logits, int r, int d, int e) { + const int lane = threadIdx.x & 31; + const int expert = blockIdx.x * 8 + (threadIdx.x >> 5); + const int row = blockIdx.y * 32 + lane; + if (expert >= e) return; + const uint16_t* xh = static_cast(x) + static_cast(row < r ? row : 0) * d; + const float* w = rows + static_cast(expert) * d; + float acc = 0.f; + for (int base = 0; base < d; base += 8) { + const uint4 xv = *reinterpret_cast(xh + base); + const uint16_t* h = reinterpret_cast(&xv); + const float4 w0 = *reinterpret_cast(w + base); + const float4 w1 = *reinterpret_cast(w + base + 4); + const float wv[8] = {w0.x, w0.y, w0.z, w0.w, w1.x, w1.y, w1.z, w1.w}; +#pragma unroll + for (int j = 0; j < 8; ++j) { + acc = fmaf(KIND == 1 ? __half2float(__ushort_as_half(h[j])) : bf16_to_float(h[j]), wv[j], acc); + } + } + if (row < r) logits[static_cast(row) * e + expert] = acc; +} + +} // namespace + +extern "C" __global__ void __launch_bounds__(256) tf_router_small_f16(const void* x, const float* rows, float* logits, + int r, int d, int e) { + router_small<1>(x, rows, logits, r, d, e); +} + +extern "C" __global__ void __launch_bounds__(256) tf_router_small_bf16(const void* x, const float* rows, float* logits, + int r, int d, int e) { + router_small<2>(x, rows, logits, r, d, e); +} + +extern "C" __global__ void __launch_bounds__(256) tf_router_tile_f16(const void* x, const float* rows, float* logits, + int r, int d, int e) { + router_tile<1>(x, rows, logits, r, d, e); +} + +extern "C" __global__ void __launch_bounds__(256) tf_router_tile_bf16(const void* x, const float* rows, float* logits, + int r, int d, int e) { + router_tile<2>(x, rows, logits, r, d, e); +} + +extern "C" __global__ void __launch_bounds__(256) tf_router_rows_f16(const void* x, const float* rows, float* logits, + int r, int d, int e) { + router_rows<1>(x, rows, logits, r, d, e); +} + +extern "C" __global__ void __launch_bounds__(256) tf_router_rows_bf16(const void* x, const float* rows, float* logits, + int r, int d, int e) { + router_rows<2>(x, rows, logits, r, d, e); +} diff --git a/zig/kernels/hip/ops/norms.hpp b/zig/kernels/hip/ops/norms.hpp new file mode 100644 index 00000000000..f6af92bedc4 --- /dev/null +++ b/zig/kernels/hip/ops/norms.hpp @@ -0,0 +1,42 @@ +#pragma once + +#include "common.hpp" + +// RMS norm rows, a wave a row. + +namespace { + +// rms_kernel's arithmetic a wave a row, 8 rows a block, so short rows do not hold a 256-thread block each. +__device__ void rms_rows(const void* x, int kind, const float* weight, void* y, int rows, int width, float eps) { + constexpr int kMost = 1024 / 32; + const int lane = threadIdx.x & 31; + const int row = blockIdx.x * 8 + (threadIdx.x >> 5); + if (row >= rows) return; + const long long at = static_cast(row) * width; + float v[kMost]; + float sum = 0.f; +#pragma unroll + for (int j = 0; j < kMost; ++j) { + const int i = lane + 32 * j; + v[j] = i < width ? load(x, kind, at + i) : 0.f; + if (i < width) sum += v[j] * v[j]; + } +#pragma unroll + for (int mask = 16; mask > 0; mask >>= 1) sum += __shfl_xor(sum, mask, 32); + const float inv = rsqrtf(__shfl(sum, 0, 32) / static_cast(width) + eps); +#pragma unroll + for (int j = 0; j < kMost; ++j) { + const int i = lane + 32 * j; + if (i >= width) break; + float value = v[j] * inv; + if (weight != nullptr) value *= weight[i]; + store(y, kind, at + i, value); + } +} + +} // namespace + +extern "C" __global__ void __launch_bounds__(256) tf_rms_rows(const void* x, int kind, const float* weight, void* y, + int rows, int width, float eps) { + rms_rows(x, kind, weight, y, rows, width, eps); +} diff --git a/zig/kernels/hip/ops/ops.hip b/zig/kernels/hip/ops/ops.hip new file mode 100644 index 00000000000..5800c0dde62 --- /dev/null +++ b/zig/kernels/hip/ops/ops.hip @@ -0,0 +1,11 @@ +// The torch-op kernels as one code object: each job's header is part of this translation unit. + +#include "common.hpp" +#include "elementwise.hpp" +#include "attention.hpp" +#include "linear.hpp" +#include "rope.hpp" +#include "norms.hpp" +#include "moe.hpp" +#include "draw.hpp" +#include "tp.hpp" diff --git a/zig/kernels/hip/ops/rope.hpp b/zig/kernels/hip/ops/rope.hpp new file mode 100644 index 00000000000..12b481e481d --- /dev/null +++ b/zig/kernels/hip/ops/rope.hpp @@ -0,0 +1,86 @@ +#pragma once + +#include "common.hpp" + +// RoPE for a prefill and the window's fused q / k norm and rotation. + +namespace { + +// apply_rope's prefill formula as torch has it, rounded to kind, stored as out_kind at h * s_head + r * s_row + j. +extern "C" __global__ void tf_rope_prefill(const void* x, int kind, void* out, int out_kind, long long s_head, long long s_row, + int len, int heads, int d, int rotary, int pos0, float theta) { + long long i = gid(); + if (i >= static_cast(len) * heads * d) return; + int j = static_cast(i % d); + int h = static_cast((i / d) % heads); + int r = static_cast(i / (static_cast(d) * heads)); + long long base = (static_cast(r) * heads + h) * d; + int half = rotary / 2; + float y; + if (j >= rotary) { + y = load(x, kind, base + j); + } else { + int f = j < half ? j : j - half; + float expo = static_cast(f) / static_cast(half); + float freq = 1.0f / powf(theta, expo); + float ang = static_cast(pos0 + r) * freq; + float c = cosf(ang), s = sinf(ang); + float x1 = load(x, kind, base + f), x2 = load(x, kind, base + f + half); + y = j < half ? x1 * c - x2 * s : x1 * s + x2 * c; + } + store(out, out_kind, h * s_head + r * s_row + j, rounded(y, kind)); +} + +// A window's q or k heads in one pass, a wave a (row, head): RMS norm, then rotation at its position, both rounded. +extern "C" __global__ void __launch_bounds__(256) tf_qk_rope(const void* src, int kind, long long s_row, int s_head, + const float* weight, float eps, int rows, int heads, int width, + int rotary, float theta, const int* pos, float* wide, + void* cache, int total) { + constexpr int kMost = 512 / 32; + __shared__ float row_v[8][512]; + const int lane = threadIdx.x & 31, wave = threadIdx.x >> 5; + const int g = blockIdx.x * 8 + wave; + const bool live = g < rows * heads; + const int r = live ? g / heads : 0, h = live ? g % heads : 0; + const long long at = r * s_row + static_cast(h) * s_head; + float v[kMost]; + float sum = 0.f; +#pragma unroll + for (int j = 0; j < kMost; ++j) { + const int i = lane + 32 * j; + v[j] = live && i < width ? load(src, kind, at + i) : 0.f; + if (i < width) sum += v[j] * v[j]; + } +#pragma unroll + for (int mask = 16; mask > 0; mask >>= 1) sum += __shfl_xor(sum, mask, 32); + const float inv = rsqrtf(__shfl(sum, 0, 32) / static_cast(width) + eps); +#pragma unroll + for (int j = 0; j < kMost; ++j) { + const int i = lane + 32 * j; + if (i < width) row_v[wave][i] = rounded(v[j] * inv * weight[i], kind); + } + __syncthreads(); + if (!live) return; + const int p = pos[r]; + const int half = rotary >> 1; + float* out = wide ? wide + static_cast(g) * width : nullptr; + const long long slot = (static_cast(h) * total + p) * width; + auto put = [&](int i, float value) { + value = rounded(value, kind); + if (out) out[i] = value; + if (cache) store(cache, kind, slot + i, value); + }; + for (int i = lane; i < half; i += 32) { + float freq = 1.f / powf(theta, static_cast(i) / static_cast(half)); + float ang = static_cast(p) * freq; + float c = cosf(ang); + float sn = sinf(ang); + float x1 = row_v[wave][i]; + float x2 = row_v[wave][half + i]; + put(i, x1 * c - x2 * sn); + put(half + i, x1 * sn + x2 * c); + } + for (int i = rotary + lane; i < width; i += 32) put(i, row_v[wave][i]); +} + +} // namespace diff --git a/zig/kernels/hip/ops/tp.hpp b/zig/kernels/hip/ops/tp.hpp new file mode 100644 index 00000000000..1b72b16a2c0 --- /dev/null +++ b/zig/kernels/hip/ops/tp.hpp @@ -0,0 +1,84 @@ +#pragma once + +#include "common.hpp" +#include "draw.hpp" + +// Tensor-parallel forward ops: residual add of an fp32 sum, expert-share remap and masks; MTP token probability. + +namespace { + +__device__ __forceinline__ long long tp_gid() { return static_cast(blockIdx.x) * blockDim.x + threadIdx.x; } + +constexpr int kProbThreads = 256; + +} // namespace + +// out = round(float(x) + y): the residual of a rank-summed fp32 share. +extern "C" __global__ void tf_add_wide(const void* x, const float* y, void* out, int kind, long long n) { + long long i = tp_gid(); + if (i >= n) return; + if (kind == 1) { + float v = __half2float(static_cast(x)[i]) + y[i]; + static_cast<__half*>(out)[i] = __float2half_rn(v); + } else { + float v = bf16_to_float(static_cast(x)[i]) + y[i]; + static_cast(out)[i] = float_to_bf16(v); + } +} + +// out[i] = the rank's local id of expert pick[i], or `skip` (an id past the rank's experts) when another rank holds it. +extern "C" __global__ void tf_moe_localize(const int* pick, const int* remap, int* out, int n, int skip) { + int i = static_cast(tp_gid()); + if (i >= n) return; + int local = remap[pick[i]]; + out[i] = local >= 0 ? local : skip; +} + +// An item of the skip expert does no work. +extern "C" __global__ void tf_moe_foreign_items(int* items, int count, int skip) { + int i = static_cast(tp_gid()); + if (i < count && items[i * 3] == skip) items[i * 3 + 2] = 0; +} + +// A pair another rank's expert answers has zero rows (selected, not multiplied: the buffer holds anything). +extern "C" __global__ void tf_moe_zero_foreign(float* y, const int* picks, int skip, long long pairs, int d) { + long long i = tp_gid(); + if (i >= pairs * d) return; + if (picks[i / d] == skip) y[i] = 0.f; +} + +// out[r] = softmax(row r)[id[r]], or of the row's largest value when `id` is null; one block a row, a NaN in gives NaN. +extern "C" __global__ void tf_token_prob(const uint16_t* logits, int kind, int n, const int* id, float* out) { + const uint16_t* row = logits + static_cast(blockIdx.x) * n; + __shared__ float shared[kProbThreads]; + float top = -INFINITY; + bool nan = false; + for (int i = threadIdx.x; i < n; i += kProbThreads) { + float v = widen(row[i], kind); + nan |= v != v; + top = fmaxf(top, v); + } + shared[threadIdx.x] = nan ? NAN : top; + __syncthreads(); + for (int stride = kProbThreads / 2; stride > 0; stride >>= 1) { + if (threadIdx.x < stride) { + float a = shared[threadIdx.x], b = shared[threadIdx.x + stride]; + shared[threadIdx.x] = (a != a || b != b) ? NAN : fmaxf(a, b); + } + __syncthreads(); + } + const float peak = shared[0]; + __syncthreads(); + float total = 0.f; + for (int i = threadIdx.x; i < n; i += kProbThreads) total += expf(widen(row[i], kind) - peak); + shared[threadIdx.x] = total; + __syncthreads(); + for (int stride = kProbThreads / 2; stride > 0; stride >>= 1) { + if (threadIdx.x < stride) shared[threadIdx.x] += shared[threadIdx.x + stride]; + __syncthreads(); + } + if (threadIdx.x == 0) { + const float chosen = id ? expf(widen(row[id[blockIdx.x]], kind) - peak) : 1.f; + out[blockIdx.x] = chosen / shared[0]; + } +} diff --git a/zig/kernels/hip/quant/act.hpp b/zig/kernels/hip/quant/act.hpp new file mode 100644 index 00000000000..e26c1cfb4c5 --- /dev/null +++ b/zig/kernels/hip/quant/act.hpp @@ -0,0 +1,26 @@ +#pragma once + +// ActEncoders feed a tile the activation rows: as the Dot's element type, or quantized once a launch with scales kept. + +#include "common/dot2.hpp" +#include "tiles/plan.hpp" + +namespace tf { +namespace rocm { + +template +struct IdentityAct { + using elem = typename T::elem; + + // Row r of the block's x (a plan's pair r reads its x row), `k` elements. + template + __device__ static const elem* row(const Args& a, int r) { + return static_cast(a.x) + x_row(a, r) * a.k; + } +}; + +using F16Act = IdentityAct; +using BF16Act = IdentityAct; + +} // namespace rocm +} // namespace tf diff --git a/zig/kernels/hip/quant/mlx.hpp b/zig/kernels/hip/quant/mlx.hpp new file mode 100644 index 00000000000..9d376a277dc --- /dev/null +++ b/zig/kernels/hip/quant/mlx.hpp @@ -0,0 +1,75 @@ +#pragma once + +// MLX affine words: y[m, n] = sum_g (scale[n, g] * sum_k x[m, k] * code[n, k] + bias[n, g] * sum_k x[m, k]). + +#include +#include +#include + +#include + +#include "tiles/plan.hpp" + +namespace tf { +namespace rocm { + +enum ScaleKind : int { kScaleF32 = 0, kScaleBF16 = 1, kScaleF16 = 2 }; + +// One (n, k / group) table of scales or biases, row major, in its stored type. +struct GroupTable { + const void* p; + int kind; // ScaleKind + __device__ float operator[](long long i) const { + if (kind == kScaleBF16) return static_cast(static_cast(p)[i]); + if (kind == kScaleF16) return __half2float(static_cast(p)[i]); + return static_cast(p)[i]; + } +}; + +struct Affine { + const void* x; // (m, k) row major, bf16 or fp16 + const uint32_t* words; // (n, k * bits / 32) row major + GroupTable scale; + GroupTable bias; + float* out; // (m, n) + int m, n, k, bits, group; + int fp16; // 0 is bf16, 1 is fp16 + Routing route = {}; + __half* out16 = nullptr; // set: the decode tile rounds each output to fp16 here instead of writing out +}; + +// A routed block takes item ``z``: its expert's weights and its rows. False when the item has no rows. +__device__ inline bool take_item(Affine& a, int z) { + if (!a.route.items) return true; + const int* item = a.route.items + 3 * z; + const int count = item[2]; + if (count <= 0) return false; + const long long expert = item[0]; + const long long groups = a.k / a.group; + const int table = a.scale.kind == kScaleF32 ? 4 : 2; + a.words += expert * a.n * (static_cast(a.k) * a.bits / 32); + a.scale.p = static_cast(a.scale.p) + expert * a.n * groups * table; + a.bias.p = static_cast(a.bias.p) + expert * a.n * groups * table; + a.route.first = item[1]; + a.m = count; + return true; +} + +__host__ __device__ inline uint32_t affine_code(const uint32_t* row, int k, int bits, int words) { + int bit = k * bits; + int word = bit >> 5; + int shift = bit & 31; + uint32_t low = row[word]; + uint32_t high = (shift + bits > 32 && word + 1 < words) ? row[word + 1] : 0u; + uint32_t value = (low >> shift); + if (shift + bits > 32) value |= high << ((32 - shift) & 31); + return value & ((1u << bits) - 1u); +} + +// Integer code as the BF16 value the product sees. 129 is not exact in BF16. +__host__ __device__ inline float code_bf16(uint32_t code) { + return static_cast(hip_bfloat16(static_cast(code))); +} + +} // namespace rocm +} // namespace tf diff --git a/zig/kernels/hip/quant/mlx_decoder.hpp b/zig/kernels/hip/quant/mlx_decoder.hpp new file mode 100644 index 00000000000..eb9a567e2c5 --- /dev/null +++ b/zig/kernels/hip/quant/mlx_decoder.hpp @@ -0,0 +1,215 @@ +#pragma once + +// The MLX affine WeightDecoder: BITS-wide codes packed little-endian in 32-bit words, a scale and a bias a group of K. + +#include +#include + +#include "common/vec.hpp" +#include "quant/mlx.hpp" +#include "quant/mlx_pieces.hpp" + +namespace tf { +namespace rocm { + +// A table entry's bits as two 16-bit loads valid for every kind; a branch or conversion would stall loads in flight. +using TableBits = unsigned __attribute__((ext_vector_type(2))); + +template +struct MlxDecoder { + using Args = Affine; + static constexpr int kBits = BITS; + // Words of a 32-code chunk of a column. + static constexpr int kWords = BITS; + + // ---- the plan: a routed item's expert and rows ---- + + __device__ static bool take_item(Args& a, int z) { return tf::rocm::take_item(a, z); } + + // ---- a column's codes ---- + + __device__ static const uint32_t* words(const Args& a) { return a.words; } + + // Words of a column's row of K codes, in the integer type the tile does its address arithmetic in. + template + __device__ static Idx row_words(const Args& a) { + return static_cast(a.k) * BITS / 32; + } + + // A chunk is BITS words: 16-byte loads when BITS % 4 == 0 and WIDE, 8-byte when even, else by word. + template + __device__ static void load(const uint32_t* src, uint32_t (&w)[BITS]) { + if constexpr (WIDE && BITS % 4 == 0) { +#pragma unroll + for (int i = 0; i < BITS / 4; ++i) { + const u32x4 v = reinterpret_cast(src)[i]; + w[4 * i] = v.x; + w[4 * i + 1] = v.y; + w[4 * i + 2] = v.z; + w[4 * i + 3] = v.w; + } + } else if constexpr (WIDE && BITS % 2 == 0) { +#pragma unroll + for (int i = 0; i < BITS / 2; ++i) { + const uint2 v = reinterpret_cast(src)[i]; + w[2 * i] = v.x; + w[2 * i + 1] = v.y; + } + } else { +#pragma unroll + for (int i = 0; i < BITS; ++i) w[i] = src[i]; + } + } + + // Two codes (below 256, exact in both types) as the activation type's pair. + template + __device__ static typename T::pair pair_of(uint32_t c0, uint32_t c1) { + if constexpr (std::is_same_v) { + // 0x6400 | c is 1024 + c in FP16; the subtraction is exact. + const uint32_t bits = (c0 | (c1 << 16)) | 0x64006400u; + return __hsub2(__builtin_bit_cast(__half2, bits), __builtin_bit_cast(__half2, 0x64006400u)); + } else { + // The float of an integer below 256 has its low 16 bits clear, so its top half is the BF16. + const uint32_t bits = (__builtin_bit_cast(uint32_t, static_cast(c0)) >> 16) | + (__builtin_bit_cast(uint32_t, static_cast(c1)) & 0xffff0000u); + return __builtin_bit_cast(typename T::pair, bits); + } + } + + // Code t of a chunk as the Dot's element type (codes are below 256, exact in both). + template + __device__ static typename T::elem code(const uint32_t (&w)[BITS], int t) { + if constexpr (std::is_same_v) { + return piece_code(w, t); + } else { + return static_cast(static_cast(piece_bits(w, t))); + } + } + + // Codes t and t + 1 of a chunk, in order, as a pair. + template + __device__ static typename T::pair pair(const uint32_t (&w)[BITS], int t) { + return pair_of(piece_bits(w, t), piece_bits(w, t + 1)); + } + + // ---- the group terms: a scale and a bias a group of a column ---- + + struct Term { + TableBits scale; + TableBits bias; + }; + + __device__ static TableBits table_bits(const GroupTable& t, long long i) { + const uint16_t* p = static_cast(t.p); + const bool wide = t.kind == kScaleF32; + return TableBits{p[wide ? 2 * i : i], p[wide ? 2 * i + 1 : i]}; + } + + __device__ static float table_float(const GroupTable& t, TableBits b) { + if (t.kind == kScaleBF16) return __uint_as_float(b.x << 16); + if (t.kind == kScaleF16) return __half2float(__ushort_as_half(static_cast(b.x))); + return __uint_as_float(b.x | (b.y << 16)); + } + + // The stored scale and bias of group `i` of a table row set (the tile does the row arithmetic). + __device__ static Term term(const Args& a, long long i) { return {table_bits(a.scale, i), table_bits(a.bias, i)}; } + + __device__ static float scale_value(const Args& a, const Term& t) { return table_float(a.scale, t.scale); } + __device__ static float bias_value(const Args& a, const Term& t) { return table_float(a.bias, t.bias); } + + // A group's sum: its dot against the codes times the scale, and the sum of x times the bias. + __device__ static float fold_scale(float acc, float dot, float scale) { return fmaf(dot, scale, acc); } + __device__ static float fold_bias(float acc, float sum_x, float bias) { return fmaf(sum_x, bias, acc); } + + // ---- the decode stream tile: a lane owns a 32-code chunk, its pairs are made with a few bit operations ---- + + // Bytes the chunk's loads are aligned to when they are wide (16 for 4-word multiples, 8 for even, else by word). + static constexpr int kWideBytes = BITS % 4 == 0 ? 16 : BITS % 2 == 0 ? 8 : 4; + + // Whether every chunk of the words is wide-aligned: the words and the row stride are. + __device__ static bool wide_aligned(const Args& a) { + const long long words_row = static_cast(a.k) * BITS / 32; + return ((reinterpret_cast(a.words) | static_cast(words_row * 4)) & (kWideBytes - 1)) == 0; + } + + // The words and tables of side s of a group of products that share x. + template + __device__ static void bind(Args& a, const Sides& sides, int s) { + a.words = sides.words[s]; + a.scale.p = sides.scale[s]; + a.bias.p = sides.bias[s]; + } + + // Codes 16 bits apart in one word when the width divides 16 (the pair is two masked fields), else neighbours. + static constexpr bool kGapPairs = BITS == 2 || BITS == 4 || BITS == 8; + + // The two codes of pair I of a chunk: `lo` and `lo + gap`. + template + static constexpr int lo() { + if constexpr (BITS == 4) return (I >> 2) * 8 + (I & 3); + else if constexpr (BITS == 8) return (I >> 1) * 4 + (I & 1); + else if constexpr (BITS == 2) return (I >> 3) * 16 + (I & 7); + else return 2 * I; + } + + static constexpr int gap() { + if constexpr (BITS == 4) return 4; + else if constexpr (BITS == 8) return 2; + else if constexpr (BITS == 2) return 8; + else return 1; + } + + // Pair I of the chunk's codes as the activation type's pair (the codes are below 256, exact in both types). + template + __device__ static typename T::pair stream_pair(const uint32_t (&w)[BITS]) { + constexpr int low = lo(); + constexpr int high = low + gap(); + uint32_t bits; + if constexpr (kGapPairs) { + constexpr int per = 32 / BITS; + constexpr uint32_t mask = ((1u << BITS) - 1u) * 0x00010001u; + bits = (w[low / per] >> (BITS * (low % per))) & mask; + } else { + bits = piece_bits(w, low) | (piece_bits(w, high) << 16); + } + if constexpr (std::is_same_v) { + bits |= 0x64006400u; + return __hsub2(__builtin_bit_cast(__half2, bits), __builtin_bit_cast(__half2, 0x64006400u)); + } else { + // The float of an integer below 256 has its low 16 bits clear, so its top half is the BF16. + const uint32_t a = __builtin_bit_cast(uint32_t, static_cast(bits & 0xffffu)); + const uint32_t b = __builtin_bit_cast(uint32_t, static_cast(bits >> 16)); + return __builtin_bit_cast(typename T::pair, (a >> 16) | (b & 0xffff0000u)); + } + } + + // The stream tile's group terms: 16-bit BF16 or FP16 table entries, loaded as stored and widened where used. + struct StreamTerms { + const unsigned short* scale; + const unsigned short* bias; + bool half; + + struct Raw { + unsigned short scale; + unsigned short bias; + }; + + __device__ explicit StreamTerms(const Args& a) + : scale(static_cast(a.scale.p)), + bias(static_cast(a.bias.p)), + half(a.scale.kind == kScaleF16) {} + + __device__ unsigned short scale_raw(long long at) const { return scale[at]; } + __device__ unsigned short bias_raw(long long at) const { return bias[at]; } + + __device__ float widen(unsigned short v) const { + return half ? __half2float(__ushort_as_half(v)) : __uint_as_float(static_cast(v) << 16); + } + + __device__ float scale_value(Raw r) const { return widen(r.scale); } + __device__ float bias_value(Raw r) const { return widen(r.bias); } + }; +}; + +} // namespace rocm +} // namespace tf diff --git a/zig/kernels/hip/quant/mlx_pieces.hpp b/zig/kernels/hip/quant/mlx_pieces.hpp new file mode 100644 index 00000000000..07c1aa43d0c --- /dev/null +++ b/zig/kernels/hip/quant/mlx_pieces.hpp @@ -0,0 +1,63 @@ +#pragma once + +// MLX affine codes read out of a 32-code piece of a column's row. + +#include + +#include + +#include "quant/mlx.hpp" + +namespace tf { +namespace rocm { + +// 32 codes are exactly BITS words: 16-byte loads when aligned and BITS % 4 == 0, 8-byte for even BITS. +template +__device__ inline void load_piece(const uint32_t* src, uint32_t (&w)[BITS]) { + const uintptr_t at = reinterpret_cast(src); + if constexpr (BITS % 4 == 0) { + if ((at & 15u) == 0) { +#pragma unroll + for (int i = 0; i < BITS / 4; ++i) { + const uint4 v = reinterpret_cast(src)[i]; + w[4 * i] = v.x; + w[4 * i + 1] = v.y; + w[4 * i + 2] = v.z; + w[4 * i + 3] = v.w; + } + return; + } + } + if constexpr (BITS % 2 == 0) { + if ((at & 7u) == 0) { +#pragma unroll + for (int i = 0; i < BITS / 2; ++i) { + const uint2 v = reinterpret_cast(src)[i]; + w[2 * i] = v.x; + w[2 * i + 1] = v.y; + } + return; + } + } +#pragma unroll + for (int i = 0; i < BITS; ++i) w[i] = src[i]; +} + +// Code t of a 32-code piece as FP16. Codes are below 256, exact in BF16 and FP16, so this is code_f16(code). +template +__device__ inline uint32_t piece_bits(const uint32_t (&w)[BITS], int t) { + const int bit = t * BITS; + const int word = bit >> 5; + const int shift = bit & 31; + uint32_t value = w[word] >> shift; + if (shift + BITS > 32) value |= w[word + 1] << (32 - shift); + return value & ((1u << BITS) - 1u); +} + +template +__device__ inline __half piece_code(const uint32_t (&w)[BITS], int t) { + return __ushort2half_rn(static_cast(piece_bits(w, t))); +} + +} // namespace rocm +} // namespace tf diff --git a/zig/kernels/hip/quant/mlx_tiles.hpp b/zig/kernels/hip/quant/mlx_tiles.hpp new file mode 100644 index 00000000000..7dacb30d3e7 --- /dev/null +++ b/zig/kernels/hip/quant/mlx_tiles.hpp @@ -0,0 +1,68 @@ +#pragma once + +// MLX affine kernels: each shared tile over the MLX decoder, identity encoder and Dot, named as the launchers look up. + +#include + +#include "quant/act.hpp" +#include "quant/mlx_decoder.hpp" +#include "tiles/dot2.hpp" +#include "tiles/epilogue.hpp" +#include "tiles/gemm.hpp" +#include "tiles/gemm_kp.hpp" +#include "tiles/matrix_gemm.hpp" +#include "tiles/stream.hpp" + +namespace tf { +namespace rocm { + +// ---- the prefill GEMM tile ---- + +template +__global__ void __launch_bounds__(256) affine_gemm_block(Affine a) { + gemm_tile, IdentityAct, T, F32Out, RT>(a); +} + +// ---- the K-parallel tiles of a short prompt ---- + +template +__global__ void __launch_bounds__(32 * WAVES) affine_gemm_kp(Affine a) { + gemm_kp_tile, IdentityAct, T, F32Out, CB, R, WAVES, RB, LOOP>(a); +} + +// ---- the prefill GEMM tile on the matrix cores of gfx11 ---- + +template +__global__ void __launch_bounds__(256) affine_wmma_gemm(Affine a) { + wmma_gemm_tile, BF16Act, WmmaBF16, F32Out>(a); +} + +// ---- the decode stream tile ---- + +// Up to four products sharing x, K, width and group in one launch; side s owns blocks [first[s], first[s + 1]). +constexpr int kStreamSides = 4; + +struct StreamSides { + const uint32_t* words[kStreamSides]; + const void* scale[kStreamSides]; + const void* bias[kStreamSides]; + void* out[kStreamSides]; + int n[kStreamSides]; + int first[kStreamSides + 1]; + int count; // 0 is the plain product of the Affine + int out_half; + int pair_cols; // > 0: the (gate | up) rows of a stacked product with this many columns each, out is its activation + float limit; // the activation's clamp when above 0 +}; + +// Item z of the plan (or the plain product, or a group's side) at CB columns a lane, R rows; PAIR fuses the activation. +template +__global__ void __launch_bounds__(32 * kStreamWaves) affine_dot2_stream(Affine a, StreamSides sides, int lpc_log2, + int gshift) { + using Epi = std::conditional_t, StreamRound>; + stream_tile, IdentityAct, T, Epi, R, CB>(a, sides, lpc_log2, gshift); +} + + +} // namespace rocm +} // namespace tf diff --git a/zig/kernels/hip/recurrence/gated_delta.hip b/zig/kernels/hip/recurrence/gated_delta.hip new file mode 100644 index 00000000000..79ab274e2ee --- /dev/null +++ b/zig/kernels/hip/recurrence/gated_delta.hip @@ -0,0 +1,302 @@ +// Gated DeltaNet: a wave per (batch, value head, value row) walks the sequence, lane sums as the Python reference. + +#include "decode/plan.hpp" + +#include + +namespace tf { +namespace rocm { + +__device__ float lane0_sum(float x) { +#pragma unroll + for (int mask = 16; mask > 0; mask >>= 1) x += __shfl_xor(x, mask, 32); + return __shfl(x, 0, 32); +} + +template +__global__ void __launch_bounds__(32) +gated_delta_kernel(const float* __restrict__ q, const float* __restrict__ k, const float* __restrict__ v, + const float* __restrict__ gate, const float* __restrict__ beta, float* __restrict__ state, + float* __restrict__ y, int length, int key_heads, int value_heads, int dv, + float* __restrict__ states) { + constexpr int SPAN = (DK + 31) / 32; + const int lane = threadIdx.x; + const int row = blockIdx.x; + const int head = blockIdx.y; + const int batch = blockIdx.z; + if (row >= dv) return; + const int key_head = head / (value_heads / key_heads); + + float s[4] = {0.f, 0.f, 0.f, 0.f}; + const size_t state_row = + ((static_cast(batch) * value_heads + head) * dv + row) * DK; +#pragma unroll + for (int i = 0; i < SPAN; ++i) { + const int idx = lane + i * 32; + if (idx < DK) s[i] = state[state_row + idx]; + } + + for (int t = 0; t < length; ++t) { + const size_t step = (static_cast(batch) * length + t) * value_heads + head; + const float decay = gate[step]; + const float step_beta = beta[step]; + const float value = v[(static_cast(batch) * length + t) * value_heads * dv + + static_cast(head) * dv + row]; + const size_t key = + ((static_cast(batch) * length + t) * key_heads + key_head) * DK; + + float remembered = 0.f; + float ks[4] = {0.f, 0.f, 0.f, 0.f}; +#pragma unroll + for (int i = 0; i < SPAN; ++i) { + const int idx = lane + i * 32; + if (idx < DK) { + ks[i] = k[key + idx]; + s[i] = s[i] * decay; + remembered = remembered + s[i] * ks[i]; + } + } + const float delta = (value - lane0_sum(remembered)) * step_beta; +#pragma unroll + for (int i = 0; i < SPAN; ++i) { + const int idx = lane + i * 32; + if (idx < DK) s[i] = s[i] + ks[i] * delta; + } + if (states != nullptr) { + const size_t snap = (((static_cast(batch) * length + t) * value_heads + head) * dv + row) * DK; +#pragma unroll + for (int i = 0; i < SPAN; ++i) { + const int idx = lane + i * 32; + if (idx < DK) states[snap + idx] = s[i]; + } + } + + float readout = 0.f; +#pragma unroll + for (int i = 0; i < SPAN; ++i) { + const int idx = lane + i * 32; + if (idx < DK) readout = readout + s[i] * q[key + idx]; + } + // Every lane has to enter the shuffle. Lane 0 owns the stored sum. + readout = lane0_sum(readout); + if (lane == 0) { + y[(static_cast(batch) * length + t) * value_heads * dv + + static_cast(head) * dv + row] = readout; + } + } + +#pragma unroll + for (int i = 0; i < SPAN; ++i) { + const int idx = lane + i * 32; + if (idx < DK) state[state_row + idx] = s[i]; + } +} + +// Value rows share a staged tile of k and q, in the wave kernel's order (-ffp-contract=off keeps it). +template +__device__ __forceinline__ void +gated_delta_tile_body(const float* __restrict__ q, const float* __restrict__ k, const float* __restrict__ v, + const float* __restrict__ gate, const float* __restrict__ beta, float* __restrict__ state, + float* __restrict__ y, int length, int key_heads, int value_heads, int dv, + float* __restrict__ states, int batch, bool write_back = true) { + constexpr int SPAN = (DK + 31) / 32; + constexpr int WIDTH = 32 * ROWS; + const int lane = threadIdx.x; + const int local = threadIdx.y; + const int row = blockIdx.x * ROWS + local; + const int head = blockIdx.y; + const int key_head = head / (value_heads / key_heads); + const int tid = local * 32 + lane; + + __shared__ float ks[STEPS][DK]; + __shared__ float qs[STEPS][DK]; + __shared__ float gs[STEPS]; + __shared__ float bs[STEPS]; + __shared__ float vs[STEPS][ROWS]; + + float s[4] = {0.f, 0.f, 0.f, 0.f}; + const size_t state_row = ((static_cast(batch) * value_heads + head) * dv + row) * DK; +#pragma unroll + for (int i = 0; i < SPAN; ++i) { + const int idx = lane + i * 32; + if (idx < DK) s[i] = state[state_row + idx]; + } + + for (int t0 = 0; t0 < length; t0 += STEPS) { + const int n = min(STEPS, length - t0); + const int nvec = n * (DK / 4); + for (int i = tid; i < nvec; i += WIDTH) { + const int elem = i * 4; + const int step = elem / DK; + const int col = elem - step * DK; + const size_t at = + ((static_cast(batch) * length + (t0 + step)) * key_heads + key_head) * DK + col; + const float4 key = *reinterpret_cast(k + at); + ks[step][col] = key.x; + ks[step][col + 1] = key.y; + ks[step][col + 2] = key.z; + ks[step][col + 3] = key.w; + // a replay (no q) advances the state alone + if (q == nullptr) continue; + const float4 query = *reinterpret_cast(q + at); + qs[step][col] = query.x; + qs[step][col + 1] = query.y; + qs[step][col + 2] = query.z; + qs[step][col + 3] = query.w; + } + for (int i = tid; i < n; i += WIDTH) { + const size_t step = (static_cast(batch) * length + (t0 + i)) * value_heads + head; + gs[i] = gate[step]; + bs[i] = beta[step]; + } + for (int i = tid; i < n * ROWS; i += WIDTH) { + const int step = i / ROWS; + const int which = i - step * ROWS; + vs[step][which] = v[((static_cast(batch) * length + (t0 + step)) * value_heads + head) * dv + + blockIdx.x * ROWS + which]; + } + __syncthreads(); + + for (int tt = 0; tt < n; ++tt) { + const float decay = gs[tt]; + const float step_beta = bs[tt]; + const float value = vs[tt][local]; + float remembered = 0.f; + float held[4] = {0.f, 0.f, 0.f, 0.f}; +#pragma unroll + for (int i = 0; i < SPAN; ++i) { + const int idx = lane + i * 32; + if (idx < DK) { + held[i] = ks[tt][idx]; + s[i] = s[i] * decay; + remembered = remembered + s[i] * held[i]; + } + } + const float delta = (value - lane0_sum(remembered)) * step_beta; +#pragma unroll + for (int i = 0; i < SPAN; ++i) { + const int idx = lane + i * 32; + if (idx < DK) s[i] = s[i] + held[i] * delta; + } + if (states != nullptr) { + const size_t snap = + (((static_cast(batch) * length + (t0 + tt)) * value_heads + head) * dv + row) * DK; +#pragma unroll + for (int i = 0; i < SPAN; ++i) { + const int idx = lane + i * 32; + if (idx < DK) states[snap + idx] = s[i]; + } + } + if (q == nullptr) continue; + float readout = 0.f; +#pragma unroll + for (int i = 0; i < SPAN; ++i) { + const int idx = lane + i * 32; + if (idx < DK) readout = readout + s[i] * qs[tt][idx]; + } + readout = lane0_sum(readout); + if (lane == 0) { + y[((static_cast(batch) * length + (t0 + tt)) * value_heads + head) * dv + row] = readout; + } + } + __syncthreads(); + } + + if (!write_back) return; +#pragma unroll + for (int i = 0; i < SPAN; ++i) { + const int idx = lane + i * 32; + if (idx < DK) state[state_row + idx] = s[i]; + } +} + +template +__global__ void __launch_bounds__(32 * ROWS) +gated_delta_tile(const float* __restrict__ q, const float* __restrict__ k, const float* __restrict__ v, + const float* __restrict__ gate, const float* __restrict__ beta, float* __restrict__ state, + float* __restrict__ y, int length, int key_heads, int value_heads, int dv, + float* __restrict__ states) { + gated_delta_tile_body(q, k, v, gate, beta, state, y, length, key_heads, value_heads, dv, states, + blockIdx.z); +} + +// A round's windows in one launch, a grid plane a slot; rows, state and snapshots come from the plan, same scan. +template +__device__ __forceinline__ void +gated_delta_plan_body(const float* q, const float* k, const float* v, const float* gate, const float* beta, float* y, + int key_heads, int value_heads, int dv, PlanArgs plan, int layer) { + const int slot = blockIdx.z; + const int length = plan.count[slot]; + if (length == 0) return; + const long long row0 = plan.first[slot]; + const unsigned long long* desc = plan_desc(plan, slot); + float* state = reinterpret_cast(desc[plan_second(layer)]); + // a window of rows leaves the state as the round found it, for its keep to replay (padding rows keep nothing) + const bool replayed = length > 1 && slot + 1 < static_cast(gridDim.z); + gated_delta_tile_body(q + row0 * key_heads * DK, k + row0 * key_heads * DK, v + row0 * value_heads * dv, + gate + row0 * value_heads, beta + row0 * value_heads, state, + y + row0 * value_heads * dv, length, key_heads, value_heads, dv, nullptr, 0, + !replayed); +} + +// A keep: each slot's state run from the round's start through its kept rows, by the same scan on the inputs kept. +template +__device__ __forceinline__ void gated_delta_replay_body(const int* keep, int rows, int key_heads, int value_heads, int dv, + PlanArgs plan, int slots) { + const int slot = blockIdx.z % slots; + const int layer = blockIdx.z / slots; + const int n = keep[slot]; + if (n <= 0 || plan.count[slot] <= 1 || plan.snaps[2 * layer + 1] == 0) return; + const long long row0 = plan.first[slot]; + const float* k = reinterpret_cast(plan.snaps[2 * layer + 1]); + const float* v = k + static_cast(rows) * key_heads * DK; + const float* gate = v + static_cast(rows) * value_heads * dv; + const float* beta = gate + static_cast(rows) * value_heads; + float* state = reinterpret_cast(plan_desc(plan, slot)[plan_second(layer)]); + gated_delta_tile_body(nullptr, k + row0 * key_heads * DK, v + row0 * value_heads * dv, + gate + row0 * value_heads, beta + row0 * value_heads, state, nullptr, n, key_heads, + value_heads, dv, nullptr, 0); +} + +} // namespace rocm +} // namespace tf + +extern "C" __global__ void __launch_bounds__(256) +tf_gdn_plan_128(const float* q, const float* k, const float* v, const float* gate, const float* beta, float* y, + int key_heads, int value_heads, int dv, PlanArgs plan, int layer) { + tf::rocm::gated_delta_plan_body<128>(q, k, v, gate, beta, y, key_heads, value_heads, dv, plan, layer); +} + +extern "C" __global__ void __launch_bounds__(256) +tf_gdn_replay_128(const int* keep, int rows, int key_heads, int value_heads, int dv, PlanArgs plan, int slots) { + tf::rocm::gated_delta_replay_body<128>(keep, rows, key_heads, value_heads, dv, plan, slots); +} + +extern "C" __global__ void __launch_bounds__(256) +tf_gdn_replay_16(const int* keep, int rows, int key_heads, int value_heads, int dv, PlanArgs plan, int slots) { + tf::rocm::gated_delta_replay_body<16>(keep, rows, key_heads, value_heads, dv, plan, slots); +} + +extern "C" __global__ void __launch_bounds__(256) +tf_gdn_plan_16(const float* q, const float* k, const float* v, const float* gate, const float* beta, float* y, + int key_heads, int value_heads, int dv, PlanArgs plan, int layer) { + tf::rocm::gated_delta_plan_body<16>(q, k, v, gate, beta, y, key_heads, value_heads, dv, plan, layer); +} + +// The template kernels launches.zig resolves. +template __global__ void tf::rocm::gated_delta_tile<128, 8, 16>(const float* __restrict__ q, + const float* __restrict__ k, const float* __restrict__ v, const float* __restrict__ gate, + const float* __restrict__ beta, float* __restrict__ state, float* __restrict__ y, int length, int key_heads, + int value_heads, int dv, float* __restrict__ states); +template __global__ void tf::rocm::gated_delta_tile<16, 8, 16>(const float* __restrict__ q, const float* __restrict__ k, + const float* __restrict__ v, const float* __restrict__ gate, const float* __restrict__ beta, + float* __restrict__ state, float* __restrict__ y, int length, int key_heads, int value_heads, int dv, + float* __restrict__ states); +template __global__ void tf::rocm::gated_delta_kernel<128>(const float* __restrict__ q, const float* __restrict__ k, + const float* __restrict__ v, const float* __restrict__ gate, const float* __restrict__ beta, + float* __restrict__ state, float* __restrict__ y, int length, int key_heads, int value_heads, int dv, + float* __restrict__ states); +template __global__ void tf::rocm::gated_delta_kernel<16>(const float* __restrict__ q, const float* __restrict__ k, + const float* __restrict__ v, const float* __restrict__ gate, const float* __restrict__ beta, + float* __restrict__ state, float* __restrict__ y, int length, int key_heads, int value_heads, int dv, + float* __restrict__ states); diff --git a/zig/kernels/hip/tiles/dot2.hip b/zig/kernels/hip/tiles/dot2.hip new file mode 100644 index 00000000000..46624c2983d --- /dev/null +++ b/zig/kernels/hip/tiles/dot2.hip @@ -0,0 +1,389 @@ +// FP16 dot2 schedules: the one-thread reference and the column, tiled, split and wide prefill tiles. + +#include "tiles/dot2.hpp" + +#include + +namespace tf { +namespace rocm { + +__device__ __half code_f16(uint32_t code) { + return __float2half_rn(code_bf16(code)); +} + +__global__ void __launch_bounds__(32) affine_dot2_kernel(Affine a) { + int col = blockIdx.x * blockDim.x + threadIdx.x; + int row = blockIdx.y; + if (row >= a.m || col >= a.n) return; + + int words = a.k * a.bits / 32; + int groups = a.k / a.group; + const uint32_t* wrow = a.words + static_cast(col) * words; + const __half* xrow = static_cast(a.x) + static_cast(row) * a.k; + float acc = 0.f; + for (int group = 0; group < groups; ++group) { + float dot = 0.f; + float sum = 0.f; + int base = group * a.group; + for (int t = 0; t < a.group; t += 2) { + __half x0 = xrow[base + t]; + __half x1 = xrow[base + t + 1]; + __half q0 = code_f16(affine_code(wrow, base + t, a.bits, words)); + __half q1 = code_f16(affine_code(wrow, base + t + 1, a.bits, words)); + dot = __builtin_amdgcn_fdot2(__halves2half2(x0, x1), __halves2half2(q0, q1), dot, false); + sum += static_cast(x0); + sum += static_cast(x1); + } + acc = fmaf(dot, a.scale[static_cast(col) * groups + group], acc); + acc = fmaf(sum, a.bias[static_cast(col) * groups + group], acc); + } + a.out[static_cast(row) * a.n + col] = acc; +} + +// Column tile: a thread owns a column and walks a staged K chunk in pair order; scale only after the whole group. +constexpr int kFastM = 8; +constexpr int kFastN = 256; +constexpr int kFastK = 64; +constexpr int kFastLd = 68; + +// fp16(bf16(code)) for every byte. Filled by code_f16 so the product rounding does not change. +__constant__ __half kByteF16[256]; + +__global__ void fill_byte_lut(__half* lut) { + int i = threadIdx.x; + if (i < 256) lut[i] = code_f16(static_cast(i)); +} + +__device__ void store_codes(__half* dst, uint32_t packed) { + dst[0] = kByteF16[packed & 0xffu]; + dst[1] = kByteF16[(packed >> 8) & 0xffu]; + dst[2] = kByteF16[(packed >> 16) & 0xffu]; + dst[3] = kByteF16[packed >> 24]; +} + +// Four packed words per load. An 8-bit group starts on a 16-byte boundary. +__device__ void load_byte_tile(__half* tile, const uint32_t* words, int words_per_row, int n, int n_cols, int tid, + int chunk, int gbase, int k0) { + int vecs = chunk >> 4; + int nvecs = n_cols * vecs; + for (int e = tid; e < nvecs; e += blockDim.x) { + int c = e / vecs; + int v = e - c * vecs; + int gc = blockIdx.x * n_cols + c; + int word = ((gbase + k0) >> 2) + (v << 2); + uint4 packed = make_uint4(0u, 0u, 0u, 0u); + if (gc < n) { + const uint32_t* src = words + static_cast(gc) * words_per_row + word; + packed = *reinterpret_cast(src); + } + int base = c * kFastLd + (v << 4); + store_codes(tile + base, packed.x); + store_codes(tile + base + 4, packed.y); + store_codes(tile + base + 8, packed.z); + store_codes(tile + base + 12, packed.w); + } +} + +// One column's chunk of codes in LDS, a 32-code piece a load; 8-bit keeps the byte path. +template +__device__ void load_piece_tile(__half* tile, const uint32_t* words, int words_per_row, int n, int n_cols, int tid, + int chunk, int gbase, int k0) { + const int pieces = chunk / 32; + for (int e = tid; e < n_cols * pieces; e += blockDim.x) { + const int c = e / pieces; + const int p = e - c * pieces; + const int gc = blockIdx.x * n_cols + c; + __half* dst = tile + c * kFastLd + p * 32; + if (gc >= n) { +#pragma unroll + for (int t = 0; t < 32; ++t) dst[t] = __float2half(0.f); + continue; + } + uint32_t w[BITS]; + load_piece(words + static_cast(gc) * words_per_row + (gbase + k0 + p * 32) / 32 * BITS, w); +#pragma unroll + for (int t = 0; t < 32; ++t) dst[t] = piece_code(w, t); + } +} + +__device__ void load_code_tile(__half* tile, const Affine& a, int words_per_row, int n_cols, int tid, int chunk, + int gbase, int k0) { + switch (a.bits) { + case 2: load_piece_tile<2>(tile, a.words, words_per_row, a.n, n_cols, tid, chunk, gbase, k0); break; + case 3: load_piece_tile<3>(tile, a.words, words_per_row, a.n, n_cols, tid, chunk, gbase, k0); break; + case 4: load_piece_tile<4>(tile, a.words, words_per_row, a.n, n_cols, tid, chunk, gbase, k0); break; + case 5: load_piece_tile<5>(tile, a.words, words_per_row, a.n, n_cols, tid, chunk, gbase, k0); break; + case 6: load_piece_tile<6>(tile, a.words, words_per_row, a.n, n_cols, tid, chunk, gbase, k0); break; + default: load_byte_tile(tile, a.words, words_per_row, a.n, n_cols, tid, chunk, gbase, k0); break; + } +} + +// Prefill tile: each output is still one thread's fdot2 chain in pair order. +constexpr int kDotBM = 16; +constexpr int kDotBN = 16; +constexpr int kDotGroup = 128; + +__global__ void affine_dot2_tiled(Affine a) { + __shared__ __half xs[kDotBM * kDotGroup]; + __shared__ __half ws[kDotBN * kDotGroup]; + int local_row = threadIdx.x / kDotBN; + int local_col = threadIdx.x % kDotBN; + int row = blockIdx.y * kDotBM + local_row; + int col = blockIdx.x * kDotBN + local_col; + int words = a.k * a.bits / 32; + int groups = a.k / a.group; + bool live = row < a.m && col < a.n; + float acc = 0.f; + const __half* x = static_cast(a.x); + + for (int group = 0; group < groups; ++group) { + int base = group * a.group; + int span = kDotBM * a.group; + for (int e = threadIdx.x; e < span; e += blockDim.x) { + int r = e / a.group; + int c = e - r * a.group; + int gr = blockIdx.y * kDotBM + r; + int gk = base + c; + __half xv = __float2half(0.f); + if (gr < a.m && gk < a.k) xv = x[static_cast(gr) * a.k + gk]; + xs[r * a.group + c] = xv; + } + for (int e = threadIdx.x; e < span; e += blockDim.x) { + int r = e / a.group; + int c = e - r * a.group; + int gc = blockIdx.x * kDotBN + r; + int gk = base + c; + __half qv = __float2half(0.f); + if (gc < a.n && gk < a.k) { + const uint32_t* wrow = a.words + static_cast(gc) * words; + qv = code_f16(affine_code(wrow, gk, a.bits, words)); + } + ws[r * a.group + c] = qv; + } + __syncthreads(); + if (live) { + float dot = 0.f; + float sum = 0.f; + const __half* xrow = xs + local_row * a.group; + const __half* wrow = ws + local_col * a.group; + for (int t = 0; t < a.group; t += 2) { + __half x0 = xrow[t]; + __half x1 = xrow[t + 1]; + __half q0 = wrow[t]; + __half q1 = wrow[t + 1]; + dot = __builtin_amdgcn_fdot2(__halves2half2(x0, x1), __halves2half2(q0, q1), dot, false); + sum += static_cast(x0); + sum += static_cast(x1); + } + int g = group; + acc = fmaf(dot, a.scale[static_cast(col) * groups + g], acc); + acc = fmaf(sum, a.bias[static_cast(col) * groups + g], acc); + } + __syncthreads(); + } + if (live) a.out[static_cast(row) * a.n + col] = acc; +} + +// affine_dot2_fast's walk over groups [z * per, (z + 1) * per); affine_dot2_fold applies them in group order. +template +__global__ void __launch_bounds__(kFastN, 1) affine_dot2_span(Affine a, float* partial, int per) { + __shared__ __half xs[Rows * kFastLd]; + __shared__ __half ws[kFastN * kFastLd]; + int tid = threadIdx.x; + int col = blockIdx.x * kFastN + tid; + int row0 = blockIdx.y * kFastM; + int words = a.k * a.bits / 32; + int groups = a.k / a.group; + int chunk = a.group < kFastK ? a.group : kFastK; + int g0 = blockIdx.z * per; + int g1 = g0 + per; + const __half* x = static_cast(a.x); + + for (int group = g0; group < g1; ++group) { + int gbase = group * a.group; + float dot[Rows]; + float sumx[Rows]; +#pragma unroll + for (int m = 0; m < Rows; ++m) { + dot[m] = 0.f; + sumx[m] = 0.f; + } + for (int k0 = 0; k0 < a.group; k0 += chunk) { + if (a.bits == 8) { + load_byte_tile(ws, a.words, words, a.n, kFastN, tid, chunk, gbase, k0); + } else { + int span = kFastN * chunk; + for (int e = tid; e < span; e += kFastN) { + int c = e / chunk; + int kk = e - c * chunk; + int gc = blockIdx.x * kFastN + c; + int gk = gbase + k0 + kk; + __half qv = __float2half(0.f); + if (gc < a.n && gk < a.k) { + const uint32_t* wrow = a.words + static_cast(gc) * words; + qv = code_f16(affine_code(wrow, gk, a.bits, words)); + } + ws[c * kFastLd + kk] = qv; + } + } + int xspan = Rows * chunk; + for (int e = tid; e < xspan; e += kFastN) { + int r = e / chunk; + int kk = e - r * chunk; + int gr = row0 + r; + int gk = gbase + k0 + kk; + __half xv = __float2half(0.f); + if (gr < a.m && gk < a.k) xv = x[static_cast(gr) * a.k + gk]; + xs[r * kFastLd + kk] = xv; + } + __syncthreads(); + if (col < a.n) { + for (int t = 0; t < chunk; t += 2) { + __half2 q = __halves2half2(ws[tid * kFastLd + t], ws[tid * kFastLd + t + 1]); +#pragma unroll + for (int m = 0; m < Rows; ++m) { + __half x0 = xs[m * kFastLd + t]; + __half x1 = xs[m * kFastLd + t + 1]; + dot[m] = __builtin_amdgcn_fdot2(__halves2half2(x0, x1), q, dot[m], false); + sumx[m] += static_cast(x0); + sumx[m] += static_cast(x1); + } + } + } + __syncthreads(); + } + if (col < a.n) { +#pragma unroll + for (int m = 0; m < Rows; ++m) { + int row = row0 + m; + if (row < a.m) { + float* slot = partial + ((static_cast(row) * a.n + col) * groups + group) * 2; + slot[0] = dot[m]; + slot[1] = sumx[m]; + } + } + } + } +} + +__global__ void __launch_bounds__(kFastN) affine_dot2_fold(const float* partial, GroupTable scale, GroupTable bias, + float* out, int m, int n, int groups) { + int col = blockIdx.x * kFastN + threadIdx.x; + int row = blockIdx.y; + if (row >= m || col >= n) return; + const float* base = partial + (static_cast(row) * n + col) * groups * 2; + float acc = 0.f; + for (int group = 0; group < groups; ++group) { + acc = fmaf(base[group * 2], scale[static_cast(col) * groups + group], acc); + acc = fmaf(base[group * 2 + 1], bias[static_cast(col) * groups + group], acc); + } + out[static_cast(row) * n + col] = acc; +} + +// Prefill tile: 128 rows share one load of 32 columns; a thread owns a column and eight rows. +constexpr int kWideM = 128; +constexpr int kWideN = 32; +constexpr int kWideRows = 8; + +__device__ void load_wide_chunk(__half* xs, __half* ws, const Affine& a, int tid, int row_base, int words, + int chunk, int gbase, int k0) { + int vecs = chunk >> 2; + int nvecs = kWideM * vecs; + for (int e = tid; e < nvecs; e += blockDim.x) { + int r = e / vecs; + int v = e - r * vecs; + int kk = v << 2; + int gr = row_base + r; + int gk = gbase + k0 + kk; + uint2 packed = make_uint2(0u, 0u); + if (gr < a.m && gk + 3 < a.k) { + const __half* src = static_cast(a.x) + static_cast(gr) * a.k + gk; + packed = *reinterpret_cast(src); + } + *reinterpret_cast(xs + r * kFastLd + kk) = packed; + } + load_code_tile(ws, a, words, kWideN, tid, chunk, gbase, k0); +} + +__device__ void dot_wide_chunk(float dot[kWideRows], float sumx[kWideRows], const __half* xs, const __half* ws, + int col_local, int row_group, int chunk) { + for (int t = 0; t < chunk; t += 2) { + __half2 q = __halves2half2(ws[col_local * kFastLd + t], ws[col_local * kFastLd + t + 1]); +#pragma unroll + for (int m = 0; m < kWideRows; ++m) { + int r = row_group * kWideRows + m; + __half x0 = xs[r * kFastLd + t]; + __half x1 = xs[r * kFastLd + t + 1]; + dot[m] = __builtin_amdgcn_fdot2(__halves2half2(x0, x1), q, dot[m], false); + sumx[m] += static_cast(x0); + sumx[m] += static_cast(x1); + } + } +} + +__global__ void __launch_bounds__(512, 1) affine_dot2_wide(Affine a) { + __shared__ __half xs[2][kWideM * kFastLd]; + __shared__ __half ws[2][kWideN * kFastLd]; + int tid = threadIdx.x; + int col_local = tid % kWideN; + int row_group = tid / kWideN; + int col = blockIdx.x * kWideN + col_local; + int row_base = blockIdx.y * kWideM; + int my_row = row_base + row_group * kWideRows; + int words = a.k * a.bits / 32; + int groups = a.k / a.group; + int chunk = a.group < kFastK ? a.group : kFastK; + int per = a.group / chunk; + int nchunks = groups * per; + float acc[kWideRows]; + float dot[kWideRows]; + float sumx[kWideRows]; +#pragma unroll + for (int m = 0; m < kWideRows; ++m) { + acc[m] = 0.f; + dot[m] = 0.f; + sumx[m] = 0.f; + } + if (nchunks > 0) load_wide_chunk(xs[0], ws[0], a, tid, row_base, words, chunk, 0, 0); + __syncthreads(); + + int phase = 0; + for (int ci = 0; ci < nchunks; ++ci) { + int next = phase ^ 1; + if (ci + 1 < nchunks) { + int nci = ci + 1; + int ng = nci / per; + int nk0 = (nci - ng * per) * chunk; + load_wide_chunk(xs[next], ws[next], a, tid, row_base, words, chunk, ng * a.group, nk0); + } + if (col < a.n) dot_wide_chunk(dot, sumx, xs[phase], ws[phase], col_local, row_group, chunk); + if ((ci % per) == per - 1 && col < a.n) { + int group = ci / per; + float scale = a.scale[static_cast(col) * groups + group]; + float biasv = a.bias[static_cast(col) * groups + group]; +#pragma unroll + for (int m = 0; m < kWideRows; ++m) { + acc[m] = fmaf(dot[m], scale, acc[m]); + acc[m] = fmaf(sumx[m], biasv, acc[m]); + dot[m] = 0.f; + sumx[m] = 0.f; + } + } + __syncthreads(); + phase = next; + } + if (col < a.n) { +#pragma unroll + for (int m = 0; m < kWideRows; ++m) { + int row = my_row + m; + if (row < a.m) a.out[static_cast(row) * a.n + col] = acc[m]; + } + } +} + +// The split tile's two row counts launches/affine.zig resolves. +template __global__ void affine_dot2_span<1>(Affine, float*, int); +template __global__ void affine_dot2_span(Affine, float*, int); + +} // namespace rocm +} // namespace tf diff --git a/zig/kernels/hip/tiles/dot2.hpp b/zig/kernels/hip/tiles/dot2.hpp new file mode 100644 index 00000000000..26d3bd4eb42 --- /dev/null +++ b/zig/kernels/hip/tiles/dot2.hpp @@ -0,0 +1,22 @@ +#pragma once + +// The tile constants shared by the dot2 files. + +#include + +#include "common/arch.hpp" +#include "common/dot2.hpp" +#include "quant/mlx.hpp" +#include "quant/mlx_pieces.hpp" + +namespace tf { +namespace rocm { + +constexpr int kLaneCols = 32; +constexpr int kLaneWaves = 8; +constexpr int kLaneRows = 8; +constexpr int kLaneGroupMax = 128; +constexpr int kBlockRows = 64; // from here the GEMM tile beats the 128-row column tile + +} // namespace rocm +} // namespace tf diff --git a/zig/kernels/hip/tiles/dot2_tiles.hip b/zig/kernels/hip/tiles/dot2_tiles.hip new file mode 100644 index 00000000000..bff70f5f72d --- /dev/null +++ b/zig/kernels/hip/tiles/dot2_tiles.hip @@ -0,0 +1,377 @@ +// Dot2 tiles for every width and both activation types: one row, 2-8 rows, the GEMM tile, and routed plans. + +#include "tiles/dot2.hpp" +#include "tiles/gemm.hpp" +#include "tiles/gemm_kp.hpp" +#include "tiles/stream.hpp" +#include "tiles/matrix_gemm.hpp" +#include "quant/mlx_tiles.hpp" + +namespace tf { +namespace rocm { + +// Groups a wave owns each round. Fewer rows leave room for more loads in flight; at most 16 code words a lane. +constexpr int lane_groups(int bits, int rows, int pieces) { + int per = rows <= 2 ? 4 : rows <= 4 ? 2 : 1; + while (per > 1 && per * pieces * bits > 8) per /= 2; + return per; +} + +template +__global__ void __launch_bounds__(kLaneCols * kLaneWaves) affine_dot2_lanes(Affine a) { + if (!take_item(a, blockIdx.z)) return; + constexpr int kGroup = 32 * PIECES; + constexpr int kPer = lane_groups(BITS, ROWS, PIECES); + constexpr int kRound = kLaneWaves * kPer; + __shared__ typename T::elem xs[ROWS][kRound * kGroup]; + __shared__ float part[kRound][ROWS][2][kLaneCols]; + const int lane = threadIdx.x % kLaneCols; + const int wave = threadIdx.x / kLaneCols; + const int col = blockIdx.x * kLaneCols + lane; + const int groups = a.k / kGroup; + const int words_row = a.k * BITS / 32; + // A lane past N reads the last column and stores nothing, so every lane reaches every barrier. + const uint32_t* wrow = a.words + static_cast(col < a.n ? col : a.n - 1) * words_row; + const typename T::elem* x = static_cast(a.x); + float acc[ROWS]; +#pragma unroll + for (int r = 0; r < ROWS; ++r) acc[r] = 0.f; + + for (int g0 = 0; g0 < groups; g0 += kRound) { + constexpr int kSpan = kRound * kGroup; + for (int e = threadIdx.x; e < ROWS * kSpan; e += blockDim.x) { + const int r = e / kSpan; + const int kk = e - r * kSpan; + const int gk = g0 * kGroup + kk; + xs[r][kk] = (r < a.m && gk < a.k) ? x[x_row(a, r) * a.k + gk] : T::zero(); + } + // 6- and 8-bit lanes load every code word of their groups up front; narrower widths load a piece at a time. + constexpr bool kAhead = BITS >= 6; + uint32_t w[kPer][PIECES][BITS]; + if constexpr (kAhead) { +#pragma unroll + for (int j = 0; j < kPer; ++j) { + const int g = g0 + wave * kPer + j; + if (g < groups) { +#pragma unroll + for (int p = 0; p < PIECES; ++p) load_piece(wrow + (g * PIECES + p) * BITS, w[j][p]); + } + } + } + __syncthreads(); +#pragma unroll + for (int j = 0; j < kPer; ++j) { + const int local = wave * kPer + j; + if (g0 + local >= groups) continue; + float dot[ROWS]; + float sum[ROWS]; +#pragma unroll + for (int r = 0; r < ROWS; ++r) { + dot[r] = 0.f; + sum[r] = 0.f; + } +#pragma unroll + for (int p = 0; p < PIECES; ++p) { + if constexpr (!kAhead) load_piece(wrow + ((g0 + local) * PIECES + p) * BITS, w[j][p]); + const int xk = local * kGroup + 32 * p; +#pragma unroll + for (int t = 0; t < 32; t += 2) { + const typename T::pair q = T::two(MlxDecoder::template code(w[j][p], t), + MlxDecoder::template code(w[j][p], t + 1)); +#pragma unroll + for (int r = 0; r < ROWS; ++r) { + const typename T::pair xp = T::two(xs[r][xk + t], xs[r][xk + t + 1]); + dot[r] = T::dot(xp, q, dot[r]); + sum[r] += T::lo(xp); + sum[r] += T::hi(xp); + } + } + } +#pragma unroll + for (int r = 0; r < ROWS; ++r) { + part[local][r][0][lane] = dot[r]; + part[local][r][1][lane] = sum[r]; + } + } + __syncthreads(); + if (wave == 0 && col < a.n) { + const int round = groups - g0 < kRound ? groups - g0 : kRound; + for (int j = 0; j < round; ++j) { + const long long at = static_cast(col) * groups + g0 + j; + const float scale = a.scale[at]; + const float bias = a.bias[at]; +#pragma unroll + for (int r = 0; r < ROWS; ++r) { + acc[r] = fmaf(part[j][r][0][lane], scale, acc[r]); + acc[r] = fmaf(part[j][r][1][lane], bias, acc[r]); + } + } + } + // The next round restages xs: wave 0's fold above only reads part. + } + if (wave == 0 && col < a.n) { +#pragma unroll + for (int r = 0; r < ROWS; ++r) { + if (r >= a.m) continue; + if (a.out16 != nullptr) { + a.out16[out_row(a, r) * a.n + col] = __float2half_rn(acc[r]); + } else { + a.out[out_row(a, r) * a.n + col] = acc[r]; + } + } + } +} + +// One-row tile: a lane owns a group, so a wave reads a weight row contiguously; lane c folds column c in order. +constexpr int kRowWaves = 4; +constexpr int kRowCols = 32; + +template +__global__ void __launch_bounds__(32 * kRowWaves) affine_dot2_row(Affine a, int lpc) { + if (!take_item(a, blockIdx.z)) return; + constexpr int kGroup = 32 * PIECES; + __shared__ float dots[kRowWaves][kRowCols][33]; + __shared__ float sums[kRowWaves][32]; + const int lane = threadIdx.x & 31; + const int wave = threadIdx.x >> 5; + const int slots = 32 / lpc; // columns a pass + const int slot = lane / lpc; + const int j = lane % lpc; + const int col0 = (blockIdx.x * kRowWaves + wave) * kRowCols; + const int mine = col0 + lane; // the column this lane folds + const int groups = a.k / kGroup; + const long long words_row = static_cast(a.k) * BITS / 32; + const typename T::pair* x = reinterpret_cast( + static_cast(a.x) + x_row(a, 0) * a.k); + float acc = 0.f; + for (int g0 = 0; g0 < groups; g0 += lpc) { + const int g = g0 + j; + const bool live = g < groups; + typename T::pair xv[PIECES * 16]; + float sum = 0.f; +#pragma unroll + for (int i = 0; i < PIECES * 16; ++i) { + xv[i] = live ? x[g * (kGroup / 2) + i] : T::two(T::zero(), T::zero()); + sum += T::lo(xv[i]); + sum += T::hi(xv[i]); + } + if (slot == 0) sums[wave][j] = sum; +#pragma unroll 2 + for (int pass = 0; pass < kRowCols / slots; ++pass) { + const int c = pass * slots + slot; + const int col = col0 + c; + float dot = 0.f; + if (live && col < a.n) { + const uint32_t* wrow = a.words + static_cast(col) * words_row + + static_cast(g) * PIECES * BITS; +#pragma unroll + for (int p = 0; p < PIECES; ++p) { + uint32_t w[BITS]; + load_piece(wrow + p * BITS, w); +#pragma unroll + for (int t = 0; t < 32; t += 2) { + const typename T::pair q = + T::two(MlxDecoder::template code(w, t), MlxDecoder::template code(w, t + 1)); + dot = T::dot(xv[p * 16 + t / 2], q, dot); + } + } + } + dots[wave][c][j] = dot; + } + __syncthreads(); + if (mine < a.n) { + const int round = groups - g0 < lpc ? groups - g0 : lpc; + for (int i = 0; i < round; ++i) { + const long long at = static_cast(mine) * groups + g0 + i; + acc = fmaf(dots[wave][lane][i], a.scale[at], acc); + acc = fmaf(sums[wave][i], a.bias[at], acc); + } + } + __syncthreads(); + } + if (mine < a.n) { + if (a.out16 != nullptr) { + a.out16[out_row(a, 0) * a.n + mine] = __float2half_rn(acc); + } else { + a.out[out_row(a, 0) * a.n + mine] = acc; + } + } +} + +// GEMM tile: 128 x 128, a thread 8 rows x 8 columns strided by 16, K through double-buffered LDS 32 codes a stage. +constexpr int kBlockM = 128; +constexpr int kBlockN = 128; +constexpr int kBlockK = 32; +constexpr int kBlockLd = kBlockK + 2; // 17 words a row: the 16 column threads of a wave read 16 banks + +template +__device__ inline void stage_block(typename T::elem* xs, typename T::elem* ws, const Affine& a, int m0, int n0, int k0, + int words_row) { + const typename T::elem* x = static_cast(a.x); + // x: 128 rows x 32 halves, 16 halves (two 16-byte loads) a thread. + { + const int r = threadIdx.x >> 1; + const int half = (threadIdx.x & 1) * 16; + const int gr = m0 + r; + uint4 lo = make_uint4(0u, 0u, 0u, 0u); + uint4 hi = lo; + if (gr < a.m) { + const uint4* src = reinterpret_cast(x + x_row(a, gr) * a.k + k0 + half); + lo = src[0]; + hi = src[1]; + } + uint32_t* dst = reinterpret_cast(xs + r * kBlockLd + half); + dst[0] = lo.x; dst[1] = lo.y; dst[2] = lo.z; dst[3] = lo.w; + dst[4] = hi.x; dst[5] = hi.y; dst[6] = hi.z; dst[7] = hi.w; + } + // Codes: one 32-code piece a column, threads 0..127. + if (threadIdx.x < kBlockN) { + const int c = threadIdx.x; + const int gc = n0 + c; + typename T::elem* dst = ws + c * kBlockLd; + if (gc < a.n) { + uint32_t w[BITS]; + load_piece(a.words + static_cast(gc) * words_row + k0 / 32 * BITS, w); +#pragma unroll + for (int t = 0; t < 32; t += 2) { + *reinterpret_cast(dst + t) = + T::two(MlxDecoder::template code(w, t), MlxDecoder::template code(w, t + 1)); + } + } else { +#pragma unroll + for (int t = 0; t < 32; t += 2) { + *reinterpret_cast(dst + t) = T::two(T::zero(), T::zero()); + } + } + } +} + +template +__global__ void __launch_bounds__(256, 1) affine_dot2_block(Affine a) { + if (!take_item(a, blockIdx.z)) return; + if (static_cast(blockIdx.y) * kBlockM >= a.m) return; + __shared__ typename T::elem xs[2][kBlockM * kBlockLd]; + __shared__ typename T::elem ws[2][kBlockN * kBlockLd]; + const int tx = threadIdx.x & 15; + const int ty = threadIdx.x >> 4; + const int m0 = blockIdx.y * kBlockM; + const int n0 = blockIdx.x * kBlockN; + const int words_row = a.k * BITS / 32; + const int groups = a.k / a.group; + const int stages = a.k / kBlockK; + const int per = a.group / kBlockK; + float acc[8][8]; + float dot[8][8]; + float sumx[8]; +#pragma unroll + for (int i = 0; i < 8; ++i) { + sumx[i] = 0.f; +#pragma unroll + for (int j = 0; j < 8; ++j) { + acc[i][j] = 0.f; + dot[i][j] = 0.f; + } + } + stage_block(xs[0], ws[0], a, m0, n0, 0, words_row); + __syncthreads(); + for (int s = 0; s < stages; ++s) { + const int cur = s & 1; + if (s + 1 < stages) stage_block(xs[cur ^ 1], ws[cur ^ 1], a, m0, n0, (s + 1) * kBlockK, words_row); + const typename T::elem* xb = xs[cur]; + const typename T::elem* wb = ws[cur]; +#pragma unroll 4 + for (int t = 0; t < kBlockK; t += 2) { + typename T::pair xv[8]; + typename T::pair wv[8]; +#pragma unroll + for (int i = 0; i < 8; ++i) { + xv[i] = *reinterpret_cast(xb + (ty + 16 * i) * kBlockLd + t); + } +#pragma unroll + for (int j = 0; j < 8; ++j) { + wv[j] = *reinterpret_cast(wb + (tx + 16 * j) * kBlockLd + t); + } +#pragma unroll + for (int i = 0; i < 8; ++i) { +#pragma unroll + for (int j = 0; j < 8; ++j) dot[i][j] = T::dot(xv[i], wv[j], dot[i][j]); + sumx[i] += T::lo(xv[i]); + sumx[i] += T::hi(xv[i]); + } + } + if (s % per == per - 1) { + const int g = s / per; +#pragma unroll + for (int j = 0; j < 8; ++j) { + const int col = n0 + tx + 16 * j; + const long long at = static_cast(col < a.n ? col : 0) * groups + g; + const float scale = a.scale[at]; + const float bias = a.bias[at]; +#pragma unroll + for (int i = 0; i < 8; ++i) { + acc[i][j] = fmaf(dot[i][j], scale, acc[i][j]); + acc[i][j] = fmaf(sumx[i], bias, acc[i][j]); + dot[i][j] = 0.f; + } + } +#pragma unroll + for (int i = 0; i < 8; ++i) sumx[i] = 0.f; + } + __syncthreads(); + } +#pragma unroll + for (int i = 0; i < 8; ++i) { + const int row = m0 + ty + 16 * i; + if (row >= a.m) continue; +#pragma unroll + for (int j = 0; j < 8; ++j) { + const int col = n0 + tx + 16 * j; + if (col < a.n) a.out[out_row(a, row) * a.n + col] = acc[i][j]; + } + } +} + +// The kernels launches/affine.zig resolves, for the build's activation type: bf16 where the GPU has its dot2. +#if TF_DOT2_BF16 +using Dot = DotBF16; +#else +using Dot = DotF16; +#endif + +#define TF_LANES(BITS, ROWS) \ + template __global__ void affine_dot2_lanes(Affine); \ + template __global__ void affine_dot2_lanes(Affine); \ + template __global__ void affine_dot2_lanes(Affine); +#define TF_STREAM(BITS, R, CB) \ + template __global__ void affine_dot2_stream(Affine, StreamSides, int, int); \ + template __global__ void affine_dot2_stream(Affine, StreamSides, int, int); +#if TF_MATRIX +#define TF_WMMA(BITS) template __global__ void affine_wmma_gemm(Affine); +#else +#define TF_WMMA(BITS) +#endif +#define TF_TILES(BITS) \ + template __global__ void affine_dot2_block(Affine); \ + template __global__ void affine_gemm_block::rt>(Affine); \ + template __global__ void affine_gemm_kp(Affine); \ + template __global__ void affine_gemm_kp(Affine); \ + template __global__ void affine_gemm_kp(Affine); \ + template __global__ void affine_gemm_kp(Affine); \ + template __global__ void affine_dot2_row(Affine, int); \ + template __global__ void affine_dot2_row(Affine, int); \ + template __global__ void affine_dot2_row(Affine, int); \ + TF_LANES(BITS, 1) TF_LANES(BITS, 2) TF_LANES(BITS, 4) TF_LANES(BITS, kLaneRows) \ + TF_STREAM(BITS, 1, 2) TF_STREAM(BITS, 1, 4) TF_STREAM(BITS, 1, 8) \ + TF_STREAM(BITS, 2, 2) TF_STREAM(BITS, 2, 4) TF_STREAM(BITS, 2, 8) \ + TF_STREAM(BITS, 4, 2) TF_STREAM(BITS, 4, 4) \ + TF_WMMA(BITS) + +TF_TILES(2) +TF_TILES(3) +TF_TILES(4) +TF_TILES(5) +TF_TILES(6) +TF_TILES(8) + +} // namespace rocm +} // namespace tf diff --git a/zig/kernels/hip/tiles/epilogue.hpp b/zig/kernels/hip/tiles/epilogue.hpp new file mode 100644 index 00000000000..6b818c008cc --- /dev/null +++ b/zig/kernels/hip/tiles/epilogue.hpp @@ -0,0 +1,86 @@ +#pragma once + +// Epilogues: what a tile does with finished sums; GEMM tiles hand one fp32 value, the stream tile a lane's columns. + +#include + +#include + +#include "tiles/plan.hpp" + +namespace tf { +namespace rocm { + +// The product in fp32 at its (row, col) of out, the plan's pair row for a routed item. +struct F32Out { + template + __device__ static void store(const Args& a, int row, int col, float v) { + a.out[out_row(a, row) * a.n + col] = v; + } +}; + +// A float as the activation type, rounded to nearest even. +template +__device__ inline typename T::elem narrow(float v) { + if constexpr (std::is_same_v) { + return __float2half_rn(v); + } else { + const uint32_t u = __float_as_uint(v); + const uint32_t bits = v != v ? 0x7fc0u : (u + (((u >> 16) & 1u) + 0x7fffu)) >> 16; + return __builtin_bit_cast(typename T::elem, static_cast(bits)); + } +} + +// A float product rounded to T: FP16 is one rounding of the exact product (fma, zero addend), never fp32 then FP16. +template +__device__ inline typename T::elem narrow_product(float a, float b) { + if constexpr (std::is_same_v) { + uint32_t bits; + asm("v_fma_mixlo_f16 %0, %1, %2, 0" : "=v"(bits) : "v"(a), "v"(b)); + return __builtin_bit_cast(typename T::elem, static_cast(bits)); + } else { + return narrow(a * b); + } +} + +// silu(gate) * up in the activation type, both clamped by limit first when it is above 0 (moe_act_kernel's arithmetic). +template +__device__ inline typename T::elem swiglu(float g, float u, float limit) { + if (limit > 0.f) { + g = fminf(g, limit); + u = fminf(fmaxf(u, -limit), limit); + } + return narrow_product(g / (1.f + expf(-g)), u); +} + +// Stream tile epilogues take a lane's CB column sums for one row (`v`), their column `c` and the paired output width. + +// The sum rounded to the activation type where `out16` is set (the decode tails' own rounding), else stored in fp32. +template +struct StreamRound { + static constexpr bool kPair = false; + + template + __device__ static void put(const Args& a, long long row, int col, const float (&v)[CB], int c, int, float) { + if (a.out16 != nullptr) { + static_cast(static_cast(a.out16))[row * a.n + col] = narrow(v[c]); + } else { + a.out[row * a.n + col] = v[c]; + } + } +}; + +// A lane's columns are CB / 2 gate columns and the same up columns; out is silu(gate) * up in T, `pair_cols` wide. +template +struct StreamSwiglu { + static constexpr bool kPair = true; + + template + __device__ static void put(const Args& a, long long row, int col, const float (&v)[CB], int c, int pair_cols, float limit) { + constexpr int CH = CB / 2; + static_cast(static_cast(a.out16))[row * pair_cols + col] = swiglu(v[c], v[c + CH], limit); + } +}; + +} // namespace rocm +} // namespace tf diff --git a/zig/kernels/hip/tiles/gemm.hpp b/zig/kernels/hip/tiles/gemm.hpp new file mode 100644 index 00000000000..de673cf5266 --- /dev/null +++ b/zig/kernels/hip/tiles/gemm.hpp @@ -0,0 +1,248 @@ +#pragma once + +// Dot2 prefill GEMM (m >= 64), 128 x 128 a block: bit for bit affine_dot2_block's per-group dot2 chain and fma fold. + +#include +#include + +#include "common/dot2.hpp" +#include "common/vec.hpp" +#include "tiles/plan.hpp" + +namespace tf { +namespace rocm { + +constexpr int kGemmM = 128; +constexpr int kGemmN = 128; +constexpr int kGemmK = 32; +constexpr int kGemmLd = kGemmK + 8; // 20 words a row: 16-byte aligned, eight 16-byte readers hit eight bank groups + +// Rows of x a lane keeps: 16 where dot2 takes x from a quad lane by DPP (RDNA2 FP16), 8 where it has none (gfx11 BF16). +template +struct GemmShape { + static constexpr int rt = 16; +}; + +template <> +struct GemmShape { + static constexpr int rt = 8; +}; + +// One 128 x 128 block of y = x . W^T: Dec reads weights and group terms, Act the rows of x, T multiplies, Epi stores. +template +__device__ __forceinline__ void gemm_tile(typename Dec::Args& a) { + if (!Dec::take_item(a, blockIdx.z)) return; + const int bx = blockIdx.x, by = blockIdx.y; + if (by * kGemmM >= a.m) return; + using pair = typename T::pair; + constexpr int kLdw = kGemmLd / 2; + __shared__ __attribute__((aligned(16))) uint32_t xs[2][kGemmM * kLdw]; + __shared__ __attribute__((aligned(16))) uint32_t ws[2][kGemmN * kLdw]; + __shared__ float sx[2][kGemmM]; + // The last three groups' scales and biases: bias lags scale a stage, so a slow wave reads an older group. + __shared__ float sc[3][kGemmN]; + __shared__ float bi[3][kGemmN]; + + const int tid = threadIdx.x; + const int m0 = by * kGemmM; + const int n0 = bx * kGemmN; + const int words_row = Dec::template row_words(a); + const int groups = a.k / a.group; + const int stages = a.k / kGemmK; + const int per = a.group / kGemmK; + const int line = tid & (kGemmN - 1); + const int side = __builtin_amdgcn_readfirstlane(tid >> 7); // codes 16 * side ..; side 1 also stages x + + // This thread's column of codes and half a row of x; past the edge it reads the last column or first row, unused. + const int col_s = n0 + line < a.n ? n0 + line : a.n - 1; + const uint32_t* wsrc = Dec::words(a) + static_cast(col_s) * words_row; + const int xrow = tid >> 1; + const int xhalf = tid & 1; + // Rows past the end are not loaded, stored or summed: a stager wave has 16 rows, a summer 32: whole waves skip. + const int wave = __builtin_amdgcn_readfirstlane(tid >> 5); + const bool xlive = wave * 16 < a.m - m0; + const bool sxlive = (line & ~31) < a.m - m0; + const int row_s = m0 + xrow < a.m ? m0 + xrow : 0; + const typename Act::elem* xrow_ptr = Act::row(a, row_s); + const u32x4* xsrc = reinterpret_cast(xrow_ptr); + + // Two stages a fetch: a row's 64 bytes of x in each (two lanes: one 128-byte request), a column's two code pieces. + uint32_t wreg[2][Dec::kWords]; + u32x4 xreg[4]; + typename Dec::Term term[2]; + float run = 0.f; + + // Every thread issues the same loads, so none waits on a branch. A stage past the last repeats it. + auto fetch = [&](int st0) { + const int st1 = st0 + 1 < stages ? st0 + 1 : stages - 1; + const int st = st0 < stages ? st0 : stages - 1; + Dec::template load(wsrc + st * Dec::kWords, wreg[0]); + Dec::template load(wsrc + st1 * Dec::kWords, wreg[1]); + const int sx_ = xhalf ? st1 : st; + if (xlive) { +#pragma unroll + for (int v = 0; v < 4; ++v) xreg[v] = xsrc[sx_ * 4 + v]; + } + const long long base = static_cast(col_s) * groups; + term[0] = Dec::term(a, base + st / per); + term[1] = Dec::term(a, base + st1 / per); + }; + // Stage st (parity J) from `buf`: this thread's 16 codes, its row of x if any, and scale and bias at a group's end. + auto stash = [&](std::integral_constant, int st, int buf) { + u32x4* dst = reinterpret_cast(ws[buf] + line * kLdw + side * 8); + auto decode = [&](std::integral_constant) { +#pragma unroll + for (int v = 0; v < 2; ++v) { + uint32_t d[4]; +#pragma unroll + for (int h = 0; h < 4; ++h) { + const int t = S * 16 + v * 8 + h * 2; + d[h] = __builtin_bit_cast(uint32_t, Dec::template pair(wreg[J], t)); + } + dst[v] = u32x4{d[0], d[1], d[2], d[3]}; + } + }; + if (side == 0) decode(std::integral_constant{}); else decode(std::integral_constant{}); + if (xhalf == J && xlive) { + u32x4* xdst = reinterpret_cast(xs[buf] + xrow * kLdw); +#pragma unroll + for (int v = 0; v < 4; ++v) xdst[v] = xreg[v]; + } + if (side == 0 && st % per == per - 1) { + sc[(st / per) % 3][line] = Dec::scale_value(a, term[J]); + bi[(st / per) % 3][line] = Dec::bias_value(a, term[J]); + } + }; + // Side 1 sums a row's x of the stage in LDS, lo then hi of each pair in order, on through the group. + auto sumx = [&](int st, int buf) { + if (st % per == 0) run = 0.f; + const u32x4* src = reinterpret_cast(xs[buf] + line * kLdw); +#pragma unroll + for (int v = 0; v < 4; ++v) { + const u32x4 u = src[v]; + const uint32_t q[4] = {u.x, u.y, u.z, u.w}; +#pragma unroll + for (int h = 0; h < 4; ++h) { + const pair p = __builtin_bit_cast(pair, q[h]); + run += T::lo(p); + run += T::hi(p); + } + } + if (st % per == per - 1) sx[(st / per) & 1][line] = run; + }; + + // A wave owns 16 rows, 128 columns; at RT = 8 lanes 0-15 take rows 0-7, 16-31 rows 8-15; x rows come by quad DPP. + constexpr int CT = 64 / RT; + const int lane = tid & 31; + // With 3 groups or fewer live, odd blocks rotate groups by 2 waves so a WGP's two blocks keep all four SIMDs busy. + const int rg = (wave + ((a.m - m0 <= 48 && (bx & 1)) ? 6 : 0)) & 7; + const bool live = rg * 16 < a.m - m0; + const int hrow = RT == 8 ? (lane >> 4) * 8 : 0; + constexpr int kCStride = RT == 8 ? 16 : 32; + const int cbase = RT == 8 ? lane & 15 : lane; + float acc[RT][CT]; + float dot[RT][CT]; +#pragma unroll + for (int r = 0; r < RT; ++r) { +#pragma unroll + for (int j = 0; j < CT; ++j) { + acc[r][j] = 0.f; + dot[r][j] = 0.f; + } + } + // A group's bias terms lag its scale terms a stage; acc is untouched until the next scale term, keeping fma order. + auto apply_bias = [&](int slot, int g) { + float s_x[RT]; +#pragma unroll + for (int r = 0; r < RT; ++r) s_x[r] = sx[g][rg * 16 + hrow + r]; +#pragma unroll + for (int j = 0; j < CT; ++j) { + const float bias = bi[slot][cbase + kCStride * j]; +#pragma unroll + for (int r = 0; r < RT; ++r) acc[r][j] = Dec::fold_bias(acc[r][j], s_x[r], bias); + } + }; + fetch(0); + stash(std::integral_constant{}, 0, 0); + __syncthreads(); + // Two stages a trip so a stage's buffer and parity are known when the code is built. + auto step = [&](std::integral_constant, int s) { + constexpr int cur = P; + if (live && s > 0 && (s - 1) % per == per - 1) apply_bias(((s - 1) / per) % 3, ((s - 1) / per) & 1); + if constexpr (P == 1) fetch(s + 1); + if (live) { + constexpr int kXRegs = RT / 4; // x words (4 pairs each) a lane loads a chunk + const uint32_t* xb = xs[cur] + (rg * 16 + hrow + (lane & 3)) * kLdw; + const uint32_t* wb = ws[cur] + cbase * kLdw; + u32x4 xr[2][kXRegs]; + u32x4 wr[2][CT]; + auto load = [&](int c, u32x4 (&xo)[kXRegs], u32x4 (&wo)[CT]) { +#pragma unroll + for (int k = 0; k < kXRegs; ++k) xo[k] = *reinterpret_cast(xb + 4 * k * kLdw + c * 4); +#pragma unroll + for (int j = 0; j < CT; ++j) wo[j] = *reinterpret_cast(wb + kCStride * j * kLdw + c * 4); + }; + load(0, xr[0], wr[0]); +#pragma unroll + for (int c = 0; c < kGemmK / 8; ++c) { + if (c + 1 < kGemmK / 8) load(c + 1, xr[(c + 1) & 1], wr[(c + 1) & 1]); +#pragma unroll + for (int q = 0; q < 4; ++q) { + uint32_t wq[CT]; +#pragma unroll + for (int j = 0; j < CT; ++j) { + const u32x4 u = wr[c & 1][j]; + wq[j] = q == 0 ? u.x : q == 1 ? u.y : q == 2 ? u.z : u.w; + } +#pragma unroll + for (int k = 0; k < kXRegs; ++k) { + const u32x4 u = xr[c & 1][k]; + const uint32_t xq = q == 0 ? u.x : q == 1 ? u.y : q == 2 ? u.z : u.w; + [&](std::integer_sequence) { + (([&] { +#pragma unroll + for (int j = 0; j < CT; ++j) { + dot[4 * k + I][j] = T::template quad(xq, wq[j], dot[4 * k + I][j]); + } + }()), + ...); + }(std::make_integer_sequence{}); + } + } + } + if (s % per == per - 1) { + const int g = (s / per) % 3; +#pragma unroll + for (int j = 0; j < CT; ++j) { + const float scale = sc[g][cbase + kCStride * j]; +#pragma unroll + for (int r = 0; r < RT; ++r) { + acc[r][j] = Dec::fold_scale(acc[r][j], dot[r][j], scale); + dot[r][j] = 0.f; + } + } + } + } + if (side == 1 && sxlive) sumx(s, cur); + stash(std::integral_constant{}, s + 1, cur ^ 1); + __syncthreads(); + }; + for (int s = 0; s < stages; s += 2) { + step(std::integral_constant{}, s); + if (s + 1 < stages) step(std::integral_constant{}, s + 1); + } + if (live && (stages - 1) % per == per - 1) apply_bias(((stages - 1) / per) % 3, ((stages - 1) / per) & 1); +#pragma unroll + for (int r = 0; r < RT; ++r) { + const int row = m0 + rg * 16 + hrow + r; + if (row >= a.m) continue; +#pragma unroll + for (int j = 0; j < CT; ++j) { + const int col = n0 + cbase + kCStride * j; + if (col < a.n) Epi::store(a, row, col, acc[r][j]); + } + } +} + +} // namespace rocm +} // namespace tf diff --git a/zig/kernels/hip/tiles/gemm_kp.hpp b/zig/kernels/hip/tiles/gemm_kp.hpp new file mode 100644 index 00000000000..d759c7da59f --- /dev/null +++ b/zig/kernels/hip/tiles/gemm_kp.hpp @@ -0,0 +1,178 @@ +#pragma once + +// Few-row prefill GEMM, a lane a column's group: outputs match affine_gemm_block bit for bit (same chains, fold order). + +#include "common/dot2.hpp" +#include "tiles/gemm.hpp" +#include "tiles/plan.hpp" + +namespace tf { +namespace rocm { + +// The lanes a column takes, a group each: 32, or 16 or 8 when it has few groups (a wave then takes more columns). +__host__ __device__ inline int kp_lanes(int groups) { return groups > 16 ? 32 : groups > 8 ? 16 : 8; } + +// CB columns a lane, R rows a pass, WAVES waves a block; passes span <= RB adjacent row blocks to share weights. +template +__device__ __forceinline__ void gemm_kp_tile(typename Dec::Args& a) { + const int blocks = (a.m + R - 1) / R < RB ? (a.m + R - 1) / R : RB; // of the launch: a routed item has its own rows + if (!Dec::take_item(a, blockIdx.z)) return; + constexpr int NO = R * CB; // outputs of a lane set + constexpr int PS = NO + 1; + constexpr int OPL = (4 * NO + 31) / 32; // outputs a lane folds, at most + const int groups = a.k / a.group; + const int gp = kp_lanes(groups); // the lanes of a set; a wave has 32 / gp sets + const int sets = 32 / gp; + const int colw = ((blockIdx.x / blocks) * WAVES + (threadIdx.x >> 5)) * CB * sets; + if (colw >= a.n) return; + __shared__ float part[WAVES][32][PS]; + __shared__ float spart[WAVES][32][R + 1]; + __shared__ float scl[WAVES][32][CB + 1]; + __shared__ float bil[WAVES][32][CB + 1]; + + const int lane = threadIdx.x & 31; + const int wave = threadIdx.x >> 5; + const int per = a.group / 32; + const int rounds = (groups + gp - 1) / gp; + const int gi = lane & (gp - 1); + const int col0 = colw + (lane / gp) * CB; // this lane's columns + const long long words_row = Dec::template row_words(a); + const uint32_t* wsrc[CB]; + long long tb[CB]; +#pragma unroll + for (int c = 0; c < CB; ++c) { + const int col = col0 + c < a.n ? col0 + c : a.n - 1; + wsrc[c] = Dec::words(a) + col * words_row; + tb[c] = static_cast(col) * groups; + } + auto pass = [&](int row0) { + const typename Act::elem* xr[R]; +#pragma unroll + for (int r = 0; r < R; ++r) xr[r] = Act::row(a, row0 + r < a.m ? row0 + r : 0); + float acc[OPL]; +#pragma unroll + for (int t = 0; t < OPL; ++t) acc[t] = 0.f; + + // Stage s of group g's code words for every column, plus its scale and bias (groups past the last repeat it). + uint32_t w[CB][Dec::kWords]; + uint32_t wn[CB][Dec::kWords]; + typename Dec::Term term[CB]; + auto fetch = [&](uint32_t (&dst)[CB][Dec::kWords], int g, int s) { + const int gl = g < groups ? g : groups - 1; +#pragma unroll + for (int c = 0; c < CB; ++c) Dec::template load(wsrc[c] + (static_cast(gl) * per + s) * Dec::kWords, dst[c]); + }; + auto tables = [&](int g) { + const int gl = g < groups ? g : groups - 1; +#pragma unroll + for (int c = 0; c < CB; ++c) term[c] = Dec::term(a, tb[c] + gl); + }; + fetch(w, gi, 0); + tables(gi); + for (int round = 0; round < rounds; ++round) { + const int g = round * gp + gi; + const int gl = g < groups ? g : groups - 1; + float d[R][CB]; + float sx[R]; +#pragma unroll + for (int r = 0; r < R; ++r) { + sx[r] = 0.f; +#pragma unroll + for (int c = 0; c < CB; ++c) d[r][c] = 0.f; + } + for (int s = 0; s < per; ++s) { + // the next stage's loads (the next round's first) go out before this stage's dots + if (s + 1 < per) fetch(wn, g, s + 1); + else if (round + 1 < rounds) fetch(wn, g + gp, 0); + typename T::pair wd[CB][16]; +#pragma unroll + for (int c = 0; c < CB; ++c) { +#pragma unroll + for (int i = 0; i < 16; ++i) { + wd[c][i] = Dec::template pair(w[c], 2 * i); + } + } +#pragma unroll + for (int r = 0; r < R; ++r) { + const u32x4* src = reinterpret_cast(xr[r] + static_cast(gl) * a.group + s * 32); + uint32_t xn[16]; +#pragma unroll + for (int v = 0; v < 4; ++v) { + const u32x4 u = src[v]; + xn[4 * v] = u.x; + xn[4 * v + 1] = u.y; + xn[4 * v + 2] = u.z; + xn[4 * v + 3] = u.w; + } + float run = sx[r]; +#pragma unroll + for (int i = 0; i < 16; ++i) { + const typename T::pair xp = __builtin_bit_cast(typename T::pair, xn[i]); + run += T::lo(xp); + run += T::hi(xp); + } + sx[r] = run; +#pragma unroll + for (int i = 0; i < 16; ++i) { + const typename T::pair xp = __builtin_bit_cast(typename T::pair, xn[i]); +#pragma unroll + for (int c = 0; c < CB; ++c) d[r][c] = T::dot(xp, wd[c][i], d[r][c]); + } + } +#pragma unroll + for (int c = 0; c < CB; ++c) { +#pragma unroll + for (int i = 0; i < Dec::kWords; ++i) w[c][i] = wn[c][i]; + } + } + // this group's results to LDS, then the round's groups in order +#pragma unroll + for (int r = 0; r < R; ++r) { + spart[wave][lane][r] = sx[r]; +#pragma unroll + for (int c = 0; c < CB; ++c) part[wave][lane][r * CB + c] = d[r][c]; + } +#pragma unroll + for (int c = 0; c < CB; ++c) { + scl[wave][lane][c] = Dec::scale_value(a, term[c]); + bil[wave][lane][c] = Dec::bias_value(a, term[c]); + } + if (round + 1 < rounds) tables(g + gp); + __syncwarp(); + const int count = groups - round * gp < gp ? groups - round * gp : gp; +#pragma unroll + for (int t = 0; t < OPL; ++t) { + const int os = lane + 32 * t; + if (os >= NO * sets) continue; + const int base = (os / NO) * gp; // the first lane of the output's set + const int o = os % NO; + const int r = o / CB; + const int c = o % CB; + float v = acc[t]; + for (int gg = 0; gg < count; ++gg) { + v = Dec::fold_scale(v, part[wave][base + gg][o], scl[wave][base + gg][c]); + v = Dec::fold_bias(v, spart[wave][base + gg][r], bil[wave][base + gg][c]); + } + acc[t] = v; + } + __syncwarp(); + } +#pragma unroll + for (int t = 0; t < OPL; ++t) { + const int os = lane + 32 * t; + if (os >= NO * sets) continue; + const int o = os % NO; + const int row = row0 + o / CB; + const int col = colw + (os / NO) * CB + o % CB; + if (row < a.m && col < a.n) Epi::store(a, row, col, acc[t]); + } + }; + if constexpr (LOOP) { + for (int row0 = (blockIdx.x % blocks) * R; row0 < a.m; row0 += blocks * R) pass(row0); + } else { + pass((blockIdx.x % blocks) * R); + } +} + +} // namespace rocm +} // namespace tf diff --git a/zig/kernels/hip/tiles/matrix_gemm.hpp b/zig/kernels/hip/tiles/matrix_gemm.hpp new file mode 100644 index 00000000000..80ec172c839 --- /dev/null +++ b/zig/kernels/hip/tiles/matrix_gemm.hpp @@ -0,0 +1,209 @@ +#pragma once + +// gfx11 WMMA prefill GEMM (BF16, m >= 16): codes are exact in BF16, so WMMA sums match the dot2 chain bit for bit. + +#include "common/wmma.hpp" +#include "tiles/gemm.hpp" +#include "tiles/plan.hpp" + +namespace tf { +namespace rocm { + +// Dec reads the words and group terms, Act the rows of x, T (a matrix-core Dot) multiplies and Epi stores. +template +__device__ __forceinline__ void wmma_gemm_tile(typename Dec::Args& a) { +#if TF_DEVICE_WMMA_GFX11 + if (!Dec::take_item(a, blockIdx.z)) return; + const int bx = blockIdx.x; + const int m0 = blockIdx.y * kGemmM; + if (m0 >= a.m) return; + constexpr int kLdw = kGemmLd / 2; + __shared__ __attribute__((aligned(16))) uint32_t xs[2][kGemmM * kLdw]; + __shared__ __attribute__((aligned(16))) uint32_t ws[2][kGemmN * kLdw]; + __shared__ float sx[2][kGemmM]; + __shared__ float sc[3][kGemmN]; + __shared__ float bi[3][kGemmN]; + + const int tid = threadIdx.x; + const int n0 = bx * kGemmN; + const int words_row = Dec::template row_words(a); + const int groups = a.k / a.group; + const int stages = a.k / kGemmK; + const int per = a.group / kGemmK; + const int rows_left = a.m - m0; + const int line = tid & (kGemmN - 1); + const int side = __builtin_amdgcn_readfirstlane(tid >> 7); + const int wave = __builtin_amdgcn_readfirstlane(tid >> 5); + const int lane = tid & 31; + + // Staging as in gemm_tile: half a column's codes and half a row of x a thread, two stages a fetch. + const int col_s = n0 + line < a.n ? n0 + line : a.n - 1; + const uint32_t* wsrc = Dec::words(a) + static_cast(col_s) * words_row; + const int xrow = tid >> 1; + const int xhalf = tid & 1; + const bool xlive = wave * 16 < rows_left; + const bool sums = side == 1 && (line & ~31) < rows_left; + const int row_s = m0 + xrow < a.m ? m0 + xrow : 0; + const typename Act::elem* xrow_ptr = Act::row(a, row_s); + const u32x4* xsrc = reinterpret_cast(xrow_ptr); + uint32_t wreg[2][Dec::kWords]; + u32x4 xreg[4]; + typename Dec::Term term[2]; + float run = 0.f; + auto fetch = [&](int st0) { + const int st1 = st0 + 1 < stages ? st0 + 1 : stages - 1; + const int st = st0 < stages ? st0 : stages - 1; + Dec::template load(wsrc + st * Dec::kWords, wreg[0]); + Dec::template load(wsrc + st1 * Dec::kWords, wreg[1]); + const int sx_ = xhalf ? st1 : st; + if (xlive) { +#pragma unroll + for (int v = 0; v < 4; ++v) xreg[v] = xsrc[sx_ * 4 + v]; + } + const long long base = static_cast(col_s) * groups; + term[0] = Dec::term(a, base + st / per); + term[1] = Dec::term(a, base + st1 / per); + }; + auto stash = [&](std::integral_constant, int st, int buf) { + u32x4* dst = reinterpret_cast(ws[buf] + line * kLdw + side * 8); + auto decode = [&](std::integral_constant) { +#pragma unroll + for (int v = 0; v < 2; ++v) { + uint32_t d[4]; +#pragma unroll + for (int h = 0; h < 4; ++h) { + const int t = S * 16 + v * 8 + h * 2; + d[h] = __builtin_bit_cast(uint32_t, Dec::template pair(wreg[J], t)); + } + dst[v] = u32x4{d[0], d[1], d[2], d[3]}; + } + }; + if (side == 0) decode(std::integral_constant{}); else decode(std::integral_constant{}); + if (xhalf == J && xlive) { + u32x4* xdst = reinterpret_cast(xs[buf] + xrow * kLdw); +#pragma unroll + for (int v = 0; v < 4; ++v) xdst[v] = xreg[v]; + } + if (side == 0 && st % per == per - 1) { + sc[(st / per) % 3][line] = Dec::scale_value(a, term[J]); + bi[(st / per) % 3][line] = Dec::bias_value(a, term[J]); + } + }; + auto sumx = [&](int st, int buf) { + if (st % per == 0) run = 0.f; + const u32x4* src = reinterpret_cast(xs[buf] + line * kLdw); +#pragma unroll + for (int v = 0; v < 4; ++v) { + const u32x4 u = src[v]; + const uint32_t q[4] = {u.x, u.y, u.z, u.w}; +#pragma unroll + for (int h = 0; h < 4; ++h) { + const typename T::pair p = __builtin_bit_cast(typename T::pair, q[h]); + run += T::lo(p); + run += T::hi(p); + } + } + if (st % per == per - 1) sx[(st / per) & 1][line] = run; + }; + + // Wave (wm, wn) owns rows 32 wm.., columns 64 wn.. (2 x 4 tiles); a lane: column lane % 16, rows 2 i + lane / 16. + const int wm = wave & 3; + const int wn = wave >> 2; + const int rl = lane & 15; + const int rh = lane >> 4; + const bool live0 = wm * 32 < rows_left; + const bool live1 = wm * 32 + 16 < rows_left; + f32x8 acc[2][4]; + f32x8 d[2][4]; +#pragma unroll + for (int mt = 0; mt < 2; ++mt) { +#pragma unroll + for (int nt = 0; nt < 4; ++nt) { + acc[mt][nt] = f32x8{0, 0, 0, 0, 0, 0, 0, 0}; + d[mt][nt] = acc[mt][nt]; + } + } + const f32x8 zero = {0, 0, 0, 0, 0, 0, 0, 0}; + auto apply_bias = [&](int slot, int g) { +#pragma unroll + for (int mt = 0; mt < 2; ++mt) { + if (mt == 1 && !live1) continue; + float s_x[8]; +#pragma unroll + for (int i = 0; i < 8; ++i) s_x[i] = sx[g][wm * 32 + mt * 16 + 2 * i + rh]; +#pragma unroll + for (int nt = 0; nt < 4; ++nt) { + const float bias = bi[slot][wn * 64 + nt * 16 + rl]; +#pragma unroll + for (int i = 0; i < 8; ++i) acc[mt][nt][i] = Dec::fold_bias(acc[mt][nt][i], s_x[i], bias); + } + } + }; + fetch(0); + stash(std::integral_constant{}, 0, 0); + __syncthreads(); + auto step = [&](std::integral_constant, int s) { + constexpr int cur = P; + if (live0 && s > 0 && (s - 1) % per == per - 1) apply_bias(((s - 1) / per) % 3, ((s - 1) / per) & 1); + if constexpr (P == 1) fetch(s + 1); + if (live0) { +#pragma unroll + for (int t = 0; t < 2; ++t) { + bf16x16 bf[4]; +#pragma unroll + for (int nt = 0; nt < 4; ++nt) bf[nt] = frag16(ws[cur] + (wn * 64 + nt * 16 + rl) * kLdw + t * 8); + const bool first = t == 0 && s % per == 0; +#pragma unroll + for (int mt = 0; mt < 2; ++mt) { + if (mt == 1 && !live1) continue; + const bf16x16 af = frag16(xs[cur] + (wm * 32 + mt * 16 + rl) * kLdw + t * 8); +#pragma unroll + for (int nt = 0; nt < 4; ++nt) { + d[mt][nt] = T::mma(af, bf[nt], first ? zero : d[mt][nt]); + } + } + } + if (s % per == per - 1) { + const int g = (s / per) % 3; +#pragma unroll + for (int mt = 0; mt < 2; ++mt) { + if (mt == 1 && !live1) continue; +#pragma unroll + for (int nt = 0; nt < 4; ++nt) { + const float scale = sc[g][wn * 64 + nt * 16 + rl]; +#pragma unroll + for (int i = 0; i < 8; ++i) acc[mt][nt][i] = Dec::fold_scale(acc[mt][nt][i], d[mt][nt][i], scale); + } + } + } + } + if (sums) sumx(s, cur); + stash(std::integral_constant{}, s + 1, cur ^ 1); + __syncthreads(); + }; + for (int s = 0; s < stages; s += 2) { + step(std::integral_constant{}, s); + if (s + 1 < stages) step(std::integral_constant{}, s + 1); + } + if (live0 && (stages - 1) % per == per - 1) apply_bias(((stages - 1) / per) % 3, ((stages - 1) / per) & 1); +#pragma unroll + for (int mt = 0; mt < 2; ++mt) { +#pragma unroll + for (int i = 0; i < 8; ++i) { + const int row = m0 + wm * 32 + mt * 16 + 2 * i + rh; + if (row >= a.m) continue; +#pragma unroll + for (int nt = 0; nt < 4; ++nt) { + const int col = n0 + wn * 64 + nt * 16 + rl; + if (col < a.n) Epi::store(a, row, col, acc[mt][nt][i]); + } + } + } +#else + (void)a; + __builtin_trap(); +#endif +} + +} // namespace rocm +} // namespace tf diff --git a/zig/kernels/hip/tiles/plan.hpp b/zig/kernels/hip/tiles/plan.hpp new file mode 100644 index 00000000000..6cd355ba754 --- /dev/null +++ b/zig/kernels/hip/tiles/plan.hpp @@ -0,0 +1,27 @@ +#pragma once + +// Routed plan, any weight format: item z = (expert, first, count) takes pairs members[first..first + count). + +namespace tf { +namespace rocm { + +struct Routing { + const int* items = nullptr; // (count, 3) int32; nullptr is one plain (m, n) product + const int* members = nullptr; + int x_div = 1; + int first = 0; // set by the kernel from its item +}; + +// Row r of this block's x and out: the plain matrix's r, or the routed item's r-th pair. +template +__device__ inline long long x_row(const Args& a, int r) { + return a.route.items ? a.route.members[a.route.first + r] / a.route.x_div : r; +} + +template +__device__ inline long long out_row(const Args& a, int r) { + return a.route.items ? a.route.members[a.route.first + r] : r; +} + +} // namespace rocm +} // namespace tf diff --git a/zig/kernels/hip/tiles/stream.hpp b/zig/kernels/hip/tiles/stream.hpp new file mode 100644 index 00000000000..d8544456771 --- /dev/null +++ b/zig/kernels/hip/tiles/stream.hpp @@ -0,0 +1,235 @@ +#pragma once + +// Streaming decode tile for 1 to 8 rows: a lane owns a 32-code chunk of a column; no LDS, lanes fold by shuffle. + +#include +#include + +#include "common/dot2.hpp" +#include "common/vec.hpp" +#include "tiles/plan.hpp" + +namespace tf { +namespace rocm { + +constexpr int kStreamWaves = 4; + +// Tile shapes that exist: CB columns a lane times R rows at most 16 accumulators. +constexpr bool stream_shape(int rows, int cb) { return cb * rows <= 16; } +constexpr int kStreamRows = 16; // the most rows a launch takes + +// The pair (half `parity` of a, half `parity` of b). +__device__ inline uint32_t stream_pick(uint32_t a, uint32_t b, int parity) { + return __builtin_amdgcn_perm(b, a, parity ? 0x07060302u : 0x05040100u); +} + +// x of one row in the order of the code pairs: pair I takes the halves of the codes it is multiplied with. +template +__device__ inline void stream_x_pairs(const uint32_t (&xn)[16], typename T::pair (&xp)[16], + std::integer_sequence) { + (([&] { + constexpr int lo = Dec::template lo(); + constexpr int hi = lo + Dec::gap(); + if constexpr (Dec::kGapPairs) { + xp[I] = __builtin_bit_cast(typename T::pair, stream_pick(xn[lo >> 1], xn[hi >> 1], lo & 1)); + } else { + xp[I] = __builtin_bit_cast(typename T::pair, xn[I]); + } + }()), + ...); +} + +// One column's chunk against RG rows: each code pair is made once and dotted with every row's x. +template +__device__ inline void stream_dots(const typename T::pair (&xp)[RG][16], const uint32_t (&w)[Dec::kWords], float (&d)[RG], + std::integer_sequence) { + (([&] { + const typename T::pair q = Dec::template stream_pair(w); +#pragma unroll + for (int r = 0; r < RG; ++r) d[r] = T::dot(xp[r][I], q, d[r]); + }()), + ...); +} + +// Epi::kPair: a lane's CB columns are CB / 2 gate columns and the same up columns; out is silu(gate) * up. +template +__device__ inline void stream_body(const typename Dec::Args& a, int lpc_log2, int gshift, int bx, int pair_cols, float limit) { + using pair = typename T::pair; + constexpr bool PAIR = Epi::kPair; + constexpr int RG = R < 4 ? R : 4; // rows a pass keeps in registers + constexpr int NG = R / RG; + constexpr uint32_t kOne = T::ones; + const int row0 = blockIdx.y * R; // a block's rows: more than 8 rows are 8-row blocks on the grid's y + const int lpc = 1 << lpc_log2; + const int lane = threadIdx.x & 31; + const int j = lane & (lpc - 1); + const int slot = lane >> lpc_log2; + constexpr int CH = PAIR ? CB / 2 : CB; // output columns a lane + const int cols = PAIR ? pair_cols : a.n; + const int per_wave = (32 >> lpc_log2) * CH; + const int col0 = (bx * kStreamWaves + (threadIdx.x >> 5)) * per_wave + slot * CH; + const int nch = a.k >> 5; + const long long words_row = Dec::template row_words(a); + const long long groups = a.k / a.group; + const uint32_t* wp[CB]; + long long sb[CB]; +#pragma unroll + for (int c = 0; c < CB; ++c) { + const int cj = PAIR ? c % CH : c; + const long long col = (col0 + cj < cols ? col0 + cj : cols - 1) + (PAIR && c >= CH ? pair_cols : 0); + wp[c] = Dec::words(a) + col * words_row; + sb[c] = col * groups; + } + const typename Act::elem* xr[R]; +#pragma unroll + for (int r = 0; r < R; ++r) xr[r] = Act::row(a, row0 + r < a.m ? row0 + r : 0); + float acc[R][CB]; +#pragma unroll + for (int r = 0; r < R; ++r) { +#pragma unroll + for (int c = 0; c < CB; ++c) acc[r][c] = 0.f; + } + + const typename Dec::StreamTerms terms(a); + + // The loads of one round: every column's chunk and its scale and bias, none waited for before the dots. + auto fetch = [&](int base, uint32_t (&w)[CB][Dec::kWords], unsigned short (&sr)[CB], unsigned short (&br)[CB]) { + const int q = base + j < nch ? base + j : nch - 1; +#pragma unroll + for (int c = 0; c < CB; ++c) { + Dec::template load(wp[c] + static_cast(q) * Dec::kWords, w[c]); + const long long at = sb[c] + (q >> gshift); + sr[c] = terms.scale_raw(at); + br[c] = terms.bias_raw(at); + } + }; + // The dots of one round. A lane past the row's last chunk read the last one: its scale and bias are zero. + auto work = [&](int base, const uint32_t (&w)[CB][Dec::kWords], const unsigned short (&sr)[CB], + const unsigned short (&br)[CB]) { + const bool live = base + j < nch; + const int q = live ? base + j : nch - 1; + float sc[CB]; + float bi[CB]; +#pragma unroll + for (int c = 0; c < CB; ++c) { + sc[c] = live ? terms.widen(sr[c]) : 0.f; + bi[c] = live ? terms.widen(br[c]) : 0.f; + } +#pragma unroll + for (int g = 0; g < NG; ++g) { + if (row0 + g * RG >= a.m) break; + pair xp[RG][16]; + float sx[RG]; +#pragma unroll + for (int r = 0; r < RG; ++r) { + uint32_t xn[16]; + const u32x4* src = + reinterpret_cast(xr[g * RG + r] + static_cast(q) * 32); +#pragma unroll + for (int v = 0; v < 4; ++v) { + const u32x4 t = src[v]; + xn[4 * v] = t.x; + xn[4 * v + 1] = t.y; + xn[4 * v + 2] = t.z; + xn[4 * v + 3] = t.w; + } + float s = 0.f; +#pragma unroll + for (int i = 0; i < 16; ++i) { + s = T::dot(__builtin_bit_cast(pair, xn[i]), __builtin_bit_cast(pair, kOne), s); + } + sx[r] = s; + stream_x_pairs(xn, xp[r], std::make_integer_sequence{}); + } +#pragma unroll + for (int c = 0; c < CB; ++c) { + float d[RG]; +#pragma unroll + for (int r = 0; r < RG; ++r) d[r] = 0.f; + stream_dots(xp, w[c], d, std::make_integer_sequence{}); +#pragma unroll + for (int r = 0; r < RG; ++r) { + acc[g * RG + r][c] = Dec::fold_scale(acc[g * RG + r][c], d[r], sc[c]); + acc[g * RG + r][c] = Dec::fold_bias(acc[g * RG + r][c], sx[r], bi[c]); + } + } + } + }; + + // Columns stagger their start round by group of 8 to spread memory channels; a column's sum order ignores shape. + const int rounds = (nch + lpc - 1) >> lpc_log2; + const int rot = rounds > 1 ? (col0 >> 3) % rounds : 0; + auto at = [&](int r) { + const int ri = r + rot >= rounds ? r + rot - rounds : r + rot; + return ri << lpc_log2; + }; + uint32_t wa[CB][Dec::kWords]; + unsigned short sa[CB], ba[CB]; + if constexpr (R == 1) { + uint32_t wb[CB][Dec::kWords]; + unsigned short sbb[CB], bbb[CB]; + fetch(at(0), wa, sa, ba); + for (int r = 0; r < rounds; r += 2) { + if (r + 1 < rounds) fetch(at(r + 1), wb, sbb, bbb); + work(at(r), wa, sa, ba); + if (r + 1 >= rounds) break; + if (r + 2 < rounds) fetch(at(r + 2), wa, sa, ba); + work(at(r + 1), wb, sbb, bbb); + } + } else { + // several rows: the dots cover the loads' latency, and registers go to the rows' x + for (int r = 0; r < rounds; ++r) { + fetch(at(r), wa, sa, ba); + work(at(r), wa, sa, ba); + } + } + +#pragma unroll + for (int r = 0; r < R; ++r) { + float v[CB]; +#pragma unroll + for (int c = 0; c < CB; ++c) { + v[c] = acc[r][c]; + for (int d = lpc >> 1; d > 0; d >>= 1) v[c] += __shfl_xor(v[c], d, 32); + } + if (j != 0 || row0 + r >= a.m) continue; +#pragma unroll + for (int c = 0; c < CH; ++c) { + const int col = col0 + c; + if (col >= cols) continue; + Epi::put(a, out_row(a, row0 + r), col, v, c, pair_cols, limit); + } + } +} + +// Item z of the plan (or plain product, or a group's side) at CB columns a lane, R rows; chunk group is q >> gshift. +template +__device__ inline void stream_tile(typename Dec::Args& a, const Sides& sides, int lpc_log2, int gshift) { + int bx = blockIdx.x; + if (sides.count > 0) { + int s = 0; + while (s + 1 < sides.count && bx >= sides.first[s + 1]) ++s; + bx -= sides.first[s]; + Dec::bind(a, sides, s); + a.n = sides.n[s]; + if (sides.out_half) { + a.out16 = static_cast<__half*>(sides.out[s]); + } else { + a.out = static_cast(sides.out[s]); + } + } + if (!Dec::take_item(a, blockIdx.z) || static_cast(blockIdx.y) * R >= a.m) return; + if constexpr (Dec::kWideBytes == 4) { + stream_body(a, lpc_log2, gshift, bx, sides.pair_cols, sides.limit); + } else { + // every chunk is wide-aligned when the words and the row stride are + if (Dec::wide_aligned(a)) { + stream_body(a, lpc_log2, gshift, bx, sides.pair_cols, sides.limit); + } else { + stream_body(a, lpc_log2, gshift, bx, sides.pair_cols, sides.limit); + } + } +} + +} // namespace rocm +} // namespace tf diff --git a/zig/src/families/qwen3_5/backend/hip/engine/draw.zig b/zig/src/families/qwen3_5/backend/hip/engine/draw.zig new file mode 100644 index 00000000000..d520e648891 --- /dev/null +++ b/zig/src/families/qwen3_5/backend/hip/engine/draw.zig @@ -0,0 +1,160 @@ +//! Tokens from logits rows on the device: argmax per greedy row, top_k + MARGIN candidates per sampled row. + +const std = @import("std"); +const hip = @import("hip"); +const lanes = @import("lanes"); +const sample = @import("sample.zig"); + +/// Most candidates a row downloads; wider requests (top_k 0, or past this) download the row and draw on the host. +pub const max_candidates = 512; + +/// One row's draw: its sampling (null is greedy), the position that keys it, the grammar's allowed bits, a host copy. +pub const Request = struct { + sampling: ?lanes.Sampling, + position: u64, + /// Structured output: only tokens whose bit is set (empty: every token). + mask: []const u32 = &.{}, + /// The row's logits copied here (the prompt's last row, kept for a masked first draw). + keep: ?[]u16 = null, +}; + +/// Whether a row is drawn on the host from the whole row. +fn whole(r: Request) bool { + return r.mask.len > 0 or r.keep != null; +} + +fn greedy(s: ?lanes.Sampling) bool { + return if (s) |x| x.temperature <= 0.0 else true; +} + +/// Candidates a sampled row asks for, or 0 when it takes the whole row. +fn candidates(s: lanes.Sampling, vocab: usize) usize { + if (s.top_k == 0) return 0; + const n = @min(vocab, @as(usize, s.top_k) + sample.MARGIN); + return if (n > max_candidates) 0 else n; +} + +fn view(comptime T: type, bytes: []u8) []T { + return std.mem.bytesAsSlice(T, @as([]align(@alignOf(T)) u8, @alignCast(bytes))); +} + +pub const Drawer = struct { + gpa: std.mem.Allocator, + d: *const hip.Runtime, + dtype: sample.Dtype, + vocab: usize, + rows: usize, + /// Per row: the candidate count, the argmax, then (rows, stride) candidate ids and value patterns. + host: hip.HostBuffer, + dev: hip.DeviceBuffer, + row: hip.HostBuffer, + + /// Device bytes a drawer of `rows` rows holds: each row's argmax and its sampling candidates. + pub fn deviceBytes(rows: usize) usize { + return rows * (8 + max_candidates * 6); + } + + pub fn init(gpa: std.mem.Allocator, d: *const hip.Runtime, dtype: sample.Dtype, vocab: usize, rows: usize) !Drawer { + const bytes = deviceBytes(rows); + var host = try hip.HostBuffer.alloc(d, bytes); + errdefer host.free(); + var dev = try hip.DeviceBuffer.alloc(d, bytes); + errdefer dev.free(); + return .{ .gpa = gpa, .d = d, .dtype = dtype, .vocab = vocab, .rows = rows, .host = host, .dev = dev, .row = try hip.HostBuffer.alloc(d, vocab * 2) }; + } + + pub fn deinit(w: *Drawer) void { + w.row.free(); + w.dev.free(); + w.host.free(); + } + + /// Row r's offsets into the scratch of `stride` candidates a row, as byte counts: ks, argmax, ids, values. + fn layout(w: *const Drawer, stride: usize) struct { arg: usize, ids: usize, vals: usize, total: usize } { + const arg = w.rows * 4; + const ids = arg + w.rows * 4; + const vals = ids + w.rows * stride * 4; + return .{ .arg = arg, .ids = ids, .vals = vals, .total = vals + w.rows * stride * 2 }; + } + + /// Where the argmax of a logits block's first rows goes on the device (a graph can hold the launch). + pub fn argmaxAt(w: *const Drawer) u64 { + return w.dev.base() + w.layout(0).arg; + } + + /// `out[r]` the token of row r of `logits` per `reqs[r]`, stream synchronized; `argmaxed`: argmax is at `argmaxAt`. + pub fn draw(w: *Drawer, o: hip.ops.Ops, stream: hip.Stream, logits: hip.ops.Tensor, reqs: []const Request, out: []u32, argmaxed: bool) !void { + const rows = reqs.len; + if (rows > w.rows) return error.WindowTooWide; + const ks = w.host.slice(i32)[0..rows]; + var stride: usize = 0; + var any_greedy = false; + for (reqs, ks) |r, *k| { + k.* = 0; + if (whole(r)) continue; + if (greedy(r.sampling)) { + any_greedy = true; + } else { + const n = candidates(r.sampling.?, w.vocab); + k.* = @intCast(n); + stride = @max(stride, n); + } + } + const at = w.layout(stride); + const base = w.dev.base(); + if (any_greedy and !argmaxed) try o.argmaxRows(logits, rows, w.vocab, base + at.arg); + if (stride > 0) { + try hip.raw.upload(w.dev, 0, std.mem.sliceAsBytes(ks), stream.handle); + try o.topkRows(logits, rows, w.vocab, base, stride, base + at.ids, base + at.vals); + } + const host = w.host.bytes; + if (any_greedy) try hip.raw.download(w.dev, at.arg, host[at.arg..][0 .. rows * 4], stream.handle); + if (stride > 0) try hip.raw.download(w.dev, at.ids, host[at.ids..at.total], stream.handle); + try stream.synchronize(); + const arg = view(i32, host[at.arg..][0 .. rows * 4]); + for (reqs, 0..) |r, i| { + if (whole(r)) { + out[i] = try w.drawWhole(stream, logits, i, r); + continue; + } + if (greedy(r.sampling)) { + out[i] = @intCast(arg[i]); + continue; + } + const s = r.sampling.?; + const n: usize = @intCast(ks[i]); + if (n == 0) { + const bytes = w.vocab * 2; + try hip.runtime.check(w.d.api.hipMemcpyDtoHAsync(w.row.bytes.ptr, @ptrFromInt(logits.ptr + i * bytes), bytes, stream.handle)); + try stream.synchronize(); + out[i] = try sample.draw(w.gpa, w.row.slice(u16)[0..w.vocab], w.dtype, s, r.position); + continue; + } + const ids = view(i32, host[at.ids + i * stride * 4 ..][0 .. n * 4]); + const vals = view(u16, host[at.vals + i * stride * 2 ..][0 .. n * 2]); + var values: [max_candidates]f64 = undefined; + var wide: [max_candidates]u64 = undefined; + for (0..n) |j| { + values[j] = sample.widen(vals, w.dtype, j); + wide[j] = @intCast(ids[j]); + } + out[i] = @intCast(try lanes.sampling.choose(w.gpa, values[0..n], wide[0..n], r.position, s)); + } + } + + /// Row `i` downloaded whole: kept if asked, masked if asked, then drawn as an unmasked whole row is. + fn drawWhole(w: *Drawer, stream: hip.Stream, logits: hip.ops.Tensor, i: usize, r: Request) !u32 { + const bytes = w.vocab * 2; + try hip.runtime.check(w.d.api.hipMemcpyDtoHAsync(w.row.bytes.ptr, @ptrFromInt(logits.ptr + i * bytes), bytes, stream.handle)); + try stream.synchronize(); + const row = w.row.slice(u16)[0..w.vocab]; + if (r.keep) |k| @memcpy(k, row); + return w.drawHost(row, r); + } + + /// A host row's token per `r`: its mask applied in place, then greedy or the keyed draw. + pub fn drawHost(w: *const Drawer, row: []u16, r: Request) !u32 { + if (r.mask.len > 0) sample.mask(row, w.dtype, r.mask); + return sample.draw(w.gpa, row, w.dtype, r.sampling, r.position); + } +}; diff --git a/zig/src/families/qwen3_5/backend/hip/engine/engine.zig b/zig/src/families/qwen3_5/backend/hip/engine/engine.zig new file mode 100644 index 00000000000..f7c770d8ea9 --- /dev/null +++ b/zig/src/families/qwen3_5/backend/hip/engine/engine.zig @@ -0,0 +1,404 @@ +//! One loaded model on one HIP device: the kernel library, a stream, scratch and the pinned buffers rounds go through. + +const std = @import("std"); +const hip = @import("hip"); +const view = @import("../model/view.zig"); +const state = @import("../forward/state.zig"); +const pages = @import("../forward/pages.zig"); +const fwd = @import("../forward/forward.zig"); +const weights = @import("../model/weights.zig"); +const bridge = @import("../model/bridge.zig"); +const sample = @import("sample.zig"); +const memory = @import("memory.zig"); +const draw = @import("draw.zig"); +const slicing = @import("../../../weights/slicing.zig"); +const reduce = @import("../forward/reduce.zig"); +const round_graphs = @import("round_graphs.zig"); +const lane_round = @import("round.zig"); +const scratch = @import("scratch.zig"); +const mtp = @import("mtp.zig"); +const admission = hip.admission; +const prefix = @import("prefix.zig"); +const plan = @import("../forward/plan.zig"); + +pub const Options = struct { + /// Most positions a stream's caches hold (its prompt, its reply and a window's rows). + capacity: usize = 0, + /// Pages of the KV pool (0: enough for `default_streams` streams of the capacity and the scratch caches). + pool_pages: usize = 0, + /// Rows a shared forward holds at most. + batch_rows: usize = 32, + /// Filled before the weights load: the pool, the bytes held and the checkpoint's share (refused when too big). + preflight: ?*Preflight = null, + /// Streams the memory plan holds at once (the lanes, or what a check runs together), and linear snapshots beside. + streams: usize = default_streams, + snapshots: usize = 0, + /// Rows one prompt pass takes at most (a longer one is refused): the server's chunk, a check's longest prompt. + prompt_rows: usize = prefix.chunk, + /// The device ordinal among the visible ones. + device: c_int = 0, + /// Positions past a reply a verify writes (the window's rows and one more). + slack: usize = 0, + /// Tensor parallelism: this rank of `world`, and the group it joined (it opens the communicator). + rank: usize = 0, + world: usize = 1, + group: ?hip.collective.Group = null, + /// Replay rounds from captured graphs (the policy's `graphs` turns it off). + graphs: bool = true, + /// What the run may use, resolved once by whoever opens the engine. + policy: hip.Policy = .{}, +}; + +pub const Pick = lane_round.Pick; + +/// Streams the pool of an engine opened without a memory plan holds whole. +pub const default_streams = 12; + +fn gib(bytes: usize) f64 { + return @as(f64, @floatFromInt(bytes)) / (1 << 30); +} + +/// What `load` found before reading the weights. +pub const Preflight = struct { pool: admission.Pool = undefined, held: u64 = 0, weights: u64 = 0 }; + +pub const Engine = struct { + pub const Rows = lane_round.Rows; + + gpa: std.mem.Allocator, + driver: hip.Runtime, + ctx: hip.Context, + lib: hip.Launcher, + stream: hip.Stream, + weights: weights.Model, + bridge: *bridge.Bridge, + o: Options, + /// The scratch below exists (`size` ran). + sized: bool, + act: view.Kind, + dtype: sample.Dtype, + /// A window's scratch, kept from its verify to its keep (the commit reads the per-row states). + rounds: hip.Arena, + /// A prompt's scratch: its rows, the step's temporaries. + prompts: hip.Arena, + ids: hip.HostBuffer, + ids_dev: hip.DeviceBuffer, + /// The keys and values of every stream and prefix entry. + pool: pages.Pool, + drawer: draw.Drawer, + /// Tensor parallelism: this rank's communicator. + comm: hip.collective.Comm = undefined, + graphs: round_graphs.Graphs, + /// The draft head's batches replay graphs (the head holds no collective, so under tp too unless graphs=off). + head_graphs: bool = true, + /// The lane rounds' plan, graph choice and keep. + round: lane_round.State = undefined, + + /// The model on the device, its scratch not yet sized: `size` takes the capacity the memory plan fits. + pub fn load(gpa: std.mem.Allocator, io: std.Io, dir: []const u8, o: Options) !*Engine { + const e = try gpa.create(Engine); + errdefer gpa.destroy(e); + e.gpa = gpa; + e.o = o; + e.sized = false; + // rounds replay graphs as the policy says; under tensor parallelism only when it is `graphs=on` + e.o.graphs = o.graphs and o.policy.graphsOn(o.world); + e.head_graphs = o.graphs and o.policy.graphsOn(1); + e.graphs = round_graphs.Graphs.init(gpa); + e.driver = try hip.Runtime.open(); + errdefer e.driver.close(); + e.ctx = try hip.Context.init(&e.driver, o.device); + errdefer e.ctx.deinit(); + const caps = try hip.Device.kernelCaps(&e.driver, o.device); + e.lib = try hip.Launcher.load(&e.driver, o.policy.choices(), hip.kernels.images); + errdefer e.lib.unload(); + e.act = if (caps.act == .f16) .f16 else .bf16; + e.dtype = if (caps.act == .f16) .f16 else .bf16; + e.stream = try hip.Stream.init(&e.driver); + errdefer e.stream.deinit(); + const group: ?slicing.Rank = if (o.world > 1) .{ .rank = o.rank, .world = o.world } else null; + if (group != null) e.comm = try (o.group orelse return error.NoGroup).open(); + errdefer if (group != null) e.comm.close(); + if (o.preflight) |pf| { + // a rank loads its share of the checkpoint, near enough to refuse before reading it + pf.* = .{ .pool = try e.budget(io), .held = hip.usage(false).device, .weights = admission.weightBytes(io, dir) / o.world }; + if (pf.weights > pf.pool.room(pf.held)) return error.WeightsDoNotFit; + } + e.weights = try weights.Model.loadRank(gpa, io, &e.driver, dir, group); + errdefer e.weights.deinit(); + e.bridge = try bridge.Bridge.init(gpa, &e.driver, &e.weights, e.act); + errdefer e.bridge.deinit(); + if (group != null) e.bridge.model.tp = e.comm; + return e; + } + + /// Allocate the scratch for streams of `capacity` positions and a pool of `pool_pages` pages (zero: the default). + pub fn size(e: *Engine, capacity: usize, pool_pages: usize) !void { + const rows = e.o.batch_rows; + const prompt_rows = @min(e.o.prompt_rows, capacity); + const count = if (pool_pages > 0) pool_pages else default_streams * pages.pagesFor(capacity) + pages.pagesFor(rows); + const arenas = try e.arenaBytes(rows, prompt_rows, capacity); + e.o.capacity = capacity; + e.o.prompt_rows = prompt_rows; + const before = hip.usage(false).device; + e.rounds = try hip.Arena.init(&e.driver, arenas[0]); + errdefer e.rounds.deinit(); + e.prompts = try hip.Arena.init(&e.driver, arenas[1]); + errdefer e.prompts.deinit(); + e.ids = try hip.HostBuffer.alloc(&e.driver, prompt_rows * 4); + errdefer e.ids.free(); + e.ids_dev = try hip.DeviceBuffer.alloc(&e.driver, prompt_rows * 4); + errdefer e.ids_dev.free(); + e.drawer = try draw.Drawer.init(e.gpa, &e.driver, e.dtype, e.bridge.model.head.n * e.o.world, rows); + errdefer e.drawer.deinit(); + e.pool = try pages.Pool.init(e.gpa, &e.driver, &e.bridge.model, count, e.o.rank == 0); + errdefer e.pool.deinit(); + e.round = try lane_round.State.init(e); + errdefer e.round.deinit(e); + const held = hip.usage(false).device - before; + const planned = e.sizedBytes(arenas, rows, prompt_rows, count); + if (held != planned) { + std.log.err("sizing held {d} device bytes, the plan says {d}", .{ held, planned }); + return error.SizeMismatch; + } + e.sized = true; + } + + /// The rounds and prompts arenas: the forwards counted at their largest shapes for `rows` and `prompt_rows`. + fn arenaBytes(e: *Engine, rows: usize, prompt_rows: usize, capacity: usize) ![2]usize { + return .{ try scratch.rounds(e, rows, capacity), try scratch.prompts(e, @min(prompt_rows, capacity), capacity) }; + } + + /// Device bytes `size` allocates beside the weights, with the arenas already counted. + fn sizedBytes(e: *const Engine, arenas: [2]usize, rows: usize, prompt_rows: usize, pool_pages: usize) usize { + const m = e.model(); + return arenas[0] + arenas[1] + prompt_rows * 4 + draw.Drawer.deviceBytes(rows) + pages.Pool.deviceBytes(m, pool_pages) + + plan.Buffer.deviceBytes(rows, m.spec.n_layers) + state.Caches.deviceBytes(m, rows); + } + + /// Device bytes `size(capacity, pool_pages)` would allocate with `rows` rows a forward: what admission weighs. + pub fn sizeBytes(e: *Engine, rows: usize, capacity: usize, pool_pages: usize) !usize { + const prompt_rows = @min(e.o.prompt_rows, capacity); + return e.sizedBytes(try e.arenaBytes(rows, prompt_rows, capacity), rows, prompt_rows, pool_pages); + } + + /// The least of each value over the ranks, the same on every rank (a window and a prompt cache they all fit). + pub fn least(e: *Engine, mine: [2]u64) ![2]u64 { + if (e.o.world < 2) return mine; + const world = e.o.world; + var host = try hip.HostBuffer.alloc(&e.driver, 16 * (1 + world)); + defer host.free(); + var send = try hip.DeviceBuffer.alloc(&e.driver, 16); + defer send.free(); + var recv = try hip.DeviceBuffer.alloc(&e.driver, 16 * world); + defer recv.free(); + host.slice(u64)[0..2].* = mine; + try send.uploadAsync(0, host.view(0, 16), e.stream); + try e.comm.allGather(send.base(), recv.base(), 2, .i64, e.stream.handle); + try recv.downloadAsync(0, host.view(16, 16 * (1 + world)), e.stream); + try e.stream.synchronize(); + var out = mine; + for (host.slice(u64)[2 .. 2 * (1 + world)], 0..) |v, i| out[i % 2] = @min(out[i % 2], v); + return out; + } + + /// Device bytes beside the weights: `size`'s scratch and pool, `streams` lanes, `snapshots`, rank 0's head. + pub fn planBytes(e: *Engine, streams: usize, rows: usize, capacity: usize, pool_pages: usize, snapshots: usize) !usize { + const m = e.model(); + const lane = state.Caches.deviceBytes(m, capacity) + m.spec.hidden * m.act.size(); + // under tensor parallelism only rank 0 holds the head + const head = if (e.o.rank > 0) 0 else try mtp.Head.deviceBytes(e.gpa, &e.driver, &e.lib, &e.weights, m, @min(rows, mtp.max_chains)); + return try e.sizeBytes(rows, capacity, pool_pages) + streams * lane + snapshots * memory.linearBytes(m.spec) + head; + } + + /// The memory a plan may take, as the native backends count it: free (host's when integrated), reserve and cap. + pub fn budget(e: *const Engine, io: std.Io) !admission.Pool { + const unified = (try e.ctx.attribute(.integrated)) != 0; + const card = try e.ctx.memInfo(); + const text = if (unified) admission.procText(e.gpa, io, "/proc/meminfo") else null; + defer if (text) |t| e.gpa.free(t); + const counts = admission.counts(unified, .{ .total = card.total, .available = card.free }, text) catch return error.HostMemoryUnavailable; + const reserve = admission.reserveBytes(getenv("TENSORFOLD_MEMORY_RESERVE_GIB"), counts.total, unified) catch return error.BadReserve; + const limit = admission.limitBytes(getenv("TENSORFOLD_HIP_MEMORY_LIMIT_GB")) catch return error.BadLimit; + return .{ .free = counts.available, .total = counts.total, .reserve = reserve, .limit = limit, .unified = unified }; + } + + /// Load and size in one: `o.capacity` positions, refused when the plan does not fit the memory. + pub fn open(gpa: std.mem.Allocator, io: std.Io, dir: []const u8, o: Options) !*Engine { + const held = hip.usage(false).device; + const e = try load(gpa, io, dir, o); + errdefer e.deinit(); + const weights_bytes = hip.usage(false).device - held; + const pool_pages = if (o.pool_pages > 0) o.pool_pages else default_streams * pages.pagesFor(o.capacity) + pages.pagesFor(o.batch_rows); + const need = try e.planBytes(o.streams, o.batch_rows, o.capacity, pool_pages, o.snapshots); + const p = try e.budget(io); + if (need > p.room(weights_bytes)) { + std.log.err("{d} streams at {d} positions with {d} rows a round need {d:.2} GiB beside the model's {d:.2} GiB, and {d:.2} GiB is left after the {d:.1} GiB reserve", .{ o.streams, o.capacity, o.batch_rows, gib(need), gib(weights_bytes), gib(p.room(weights_bytes)), gib(p.reserve) }); + return error.OutOfDeviceMemory; + } + try e.size(o.capacity, pool_pages); + return e; + } + + pub fn deinit(e: *Engine) void { + e.stream.synchronize() catch {}; + if (e.graphs.captured > 0) std.log.info("graphs: {d} captured ({d:.0} ms each), {d} of {d} rounds replayed", .{ e.graphs.captured, @as(f64, @floatFromInt(e.graphs.capture_ns)) / @as(f64, @floatFromInt(e.graphs.captured)) / 1e6, e.graphs.replayed, e.graphs.rounds }); + e.graphs.deinit(); + if (e.sized) { + e.round.deinit(e); + e.drawer.deinit(); + e.ids_dev.free(); + e.ids.free(); + e.prompts.deinit(); + e.rounds.deinit(); + e.pool.deinit(); + } + e.bridge.deinit(); + e.weights.deinit(); + e.stream.deinit(); + e.lib.unload(); + if (e.o.world > 1) e.comm.close(); + e.ctx.deinit(); + e.driver.close(); + e.gpa.destroy(e); + } + + pub fn model(e: *const Engine) *const view.Model { + return &e.bridge.model; + } + + pub fn ops(e: *Engine, arena: *hip.Arena) hip.ops.Ops { + return .{ .l = &e.lib, .bf16 = e.act == .bf16, .stream = e.stream.handle, .arena = arena }; + } + + /// Caches for `total` positions (at most the capacity) with every page taken. + pub fn newCaches(e: *Engine, total: usize) !state.Caches { + return state.Caches.initFull(e.gpa, &e.pool, e.model(), @min(total, e.o.capacity)); + } + + /// Caches for `total` positions (at most the capacity) with no page yet: a stream takes them as it grows. + pub fn emptyCaches(e: *Engine, total: usize) !state.Caches { + return state.Caches.init(e.gpa, &e.pool, e.model(), @min(total, e.o.capacity)); + } + + /// Whether the draft head's greedy batches replay graphs. + pub fn headGraphs(e: *const Engine) bool { + return if (e.o.world > 1) e.head_graphs else e.o.graphs; + } + + /// Waits for the stream, before caches are freed (a round may still be running on them). + pub fn drain(e: *Engine) void { + e.stream.synchronize() catch {}; + } + + /// The tokens of `rows` final rows at `hidden`: one projection, vocabulary slices joined in rank order. + fn project(e: *Engine, o: hip.ops.Ops, hidden: hip.ops.Tensor, rows: usize, reqs: []const draw.Request, out: []u32) !void { + const y = try o.project(hidden, e.model().head, rows, false); + try e.drawRows(o, y, rows, reqs, out, false); + } + + /// Each of `rows` logits rows drawn per `reqs`, whole rows joined first across ranks; `argmaxed`: greedy rows done. + pub fn drawRows(e: *Engine, o: hip.ops.Ops, y: hip.ops.Tensor, rows: usize, reqs: []const draw.Request, out: []u32, argmaxed: bool) !void { + try e.drawer.draw(o, e.stream, try e.wholeRows(o, y, rows), reqs[0..rows], out, argmaxed); + } + + /// `rows` logits rows whole: this rank's when it holds the whole head, else every rank's slices joined. + pub fn wholeRows(e: *Engine, o: hip.ops.Ops, y: hip.ops.Tensor, rows: usize) !hip.ops.Tensor { + return if (e.model().tp) |c| e.joined(o, c, y, rows) else y; + } + + /// vocab_gather: every rank's slice of `rows` logits rows, joined on the device into whole rows in rank order. + fn joined(e: *Engine, o: hip.ops.Ops, c: hip.collective.Comm, slice: hip.ops.Tensor, rows: usize) !hip.ops.Tensor { + const width = e.model().head.n; + const n = rows * width; + const size_of = slice.kind.size(); + const parts = try o.arena.take(c.world * n * size_of); + try reduce.gather(o, c, slice, parts, n); + const whole = try o.arena.take(c.world * n * size_of); + for (0..rows) |row| for (0..c.world) |r| { + const to = whole + (row * c.world + r) * width * size_of; + const from = parts + (r * rows + row) * width * size_of; + if (o.stream != hip.counting) try hip.runtime.check(e.driver.api.hipMemcpyDtoDAsync(@ptrFromInt(to), @ptrFromInt(from), width * size_of, o.stream)); + }; + return .{ .ptr = whole, .kind = slice.kind }; + } + + /// Asked after each layer of a long prompt (the stream is idle then): true ends the pass with `error.Cancelled`. + pub const Cancel = struct { + ctx: *anyopaque, + check: *const fn (ctx: *anyopaque) bool, + }; + + const Poll = struct { + stream: hip.Stream, + cancel: Cancel, + + fn layer(ctx: *anyopaque, _: usize, _: hip.ops.Tensor, _: usize) anyerror!void { + const p: *Poll = @ptrCast(@alignCast(ctx)); + try p.stream.synchronize(); + if (p.cancel.check(p.cancel.ctx)) return error.Cancelled; + } + }; + + /// The pass over `len` rows polling the cancel after each layer; null where it cannot stop (a short prompt, or tp). + fn poll(e: *Engine, cancel: ?Cancel, len: usize, p: *Poll) ?fwd.Trace { + const c = cancel orelse return null; + if (e.o.world > 1 or len < fwd.SPAN) return null; + p.* = .{ .stream = e.stream, .cancel = c }; + return .{ .ctx = p, .layer = Poll.layer }; + } + + /// Run `prompt[pos0..end]` into `caches`, its logits not read: a cut where the caches are kept. + pub fn advance(e: *Engine, caches: *state.Caches, prompt: []const u32, pos0: usize, end: usize, cancel: ?Cancel) !void { + if (end <= pos0 or end > caches.total or end - pos0 > e.o.prompt_rows) return error.PromptTooLong; + e.prompts.reset(); + const ids = e.ids.slice(u32)[0 .. end - pos0]; + @memcpy(ids, prompt[pos0..end]); + try e.ids_dev.uploadAsync(0, e.ids.view(0, 4 * ids.len), e.stream); + var p: Poll = undefined; + _ = try fwd.span(e.ops(&e.prompts), e.model(), caches, e.ids_dev.base(), end - pos0, pos0, e.poll(cancel, end - pos0, &p)); + try e.stream.synchronize(); + } + + /// Prefill `prompt[pos0..]` into `caches`; the last row's token, its final row copied to `last` (MTP's input). + pub fn prefill(e: *Engine, caches: *state.Caches, prompt: []const u32, pos0: usize, last: ?hip.DeviceBuffer, req: draw.Request, cancel: ?Cancel) !u32 { + const m = e.model(); + const len = prompt.len - pos0; + if (len == 0 or prompt.len > caches.total or len > e.o.prompt_rows) return error.PromptTooLong; + e.prompts.reset(); + const ids = e.ids.slice(u32)[0..len]; + @memcpy(ids, prompt[pos0..]); + try e.ids_dev.uploadAsync(0, e.ids.view(0, 4 * ids.len), e.stream); + const o = e.ops(&e.prompts); + var p: Poll = undefined; + const hidden = try fwd.span(o, m, caches, e.ids_dev.base(), len, pos0, e.poll(cancel, len, &p)); + const row = fwd.at(hidden, (len - 1) * m.spec.hidden); + if (last) |b| try hip.raw.copy(b, 0, row.ptr, m.spec.hidden * m.act.size(), e.stream.handle); + var token: [1]u32 = undefined; + try e.project(o, row, 1, &.{req}, &token); + return token[0]; + } + + /// Every window in one forward: `out` the token of every row; the round's snapshots live until its keeps flush. + pub fn verify(e: *Engine, rows: []const Rows, reqs: []const draw.Request, out: []u32) !lane_round.Verified { + return lane_round.verify(e, rows, reqs, out); + } + + /// The round's graph choice: from the shape's history, or `forced` (rank 0's pick, which a follower obeys). + pub fn choose(e: *Engine, rows: []const Rows, forced: ?Pick) !Pick { + return lane_round.choose(e, rows, forced); + } + + /// Marks a slot of the last verify to keep its first `rows` rows at the next `flush`. + pub fn keep(e: *Engine, slot: usize, rows: usize) void { + lane_round.mark(e, slot, rows); + } + + /// Keeps every marked slot in one launch. + pub fn flush(e: *Engine) !void { + try lane_round.flush(e); + } +}; + +fn getenv(name: [:0]const u8) ?[]const u8 { + return std.mem.span(std.c.getenv(name) orelse return null); +} diff --git a/zig/src/families/qwen3_5/backend/hip/engine/graph_cache.zig b/zig/src/families/qwen3_5/backend/hip/engine/graph_cache.zig new file mode 100644 index 00000000000..9d46c078663 --- /dev/null +++ b/zig/src/families/qwen3_5/backend/hip/engine/graph_cache.zig @@ -0,0 +1,98 @@ +//! Captured graphs by shape: a launch sequence recorded the second time its shape is met, replayed on every later one. + +const std = @import("std"); +const hip = @import("hip"); + +/// Shapes kept at once; the least recently used one is dropped for a new one. +const max_entries = 64; + +pub const State = enum { seen, ready, failed }; + +/// A cache of graphs keyed by `Key` (plain integers and booleans), each with the `Out` its capture produced. +pub fn Cache(comptime Key: type, comptime Out: type) type { + return struct { + const Self = @This(); + + pub const Entry = struct { + key: Key, + state: State = .seen, + exec: ?hip.graph.Exec = null, + out: Out = undefined, + tick: u64 = 0, + }; + + gpa: std.mem.Allocator, + entries: std.ArrayList(Entry) = .empty, + clock: u64 = 0, + /// Launches run, replayed and captured; the host's nanoseconds from a launch's start to its work queued. + rounds: u64 = 0, + submit_ns: u64 = 0, + /// The host's nanoseconds recording and instantiating graphs. + capture_ns: u64 = 0, + replayed: u64 = 0, + captured: u64 = 0, + + pub fn init(gpa: std.mem.Allocator) Self { + return .{ .gpa = gpa }; + } + + pub fn deinit(g: *Self) void { + for (g.entries.items) |*e| if (e.exec) |*x| x.deinit(); + g.entries.deinit(g.gpa); + } + + /// The entry for `key`, made (state `seen`) if new. + pub fn find(g: *Self, key: Key) !*Entry { + g.clock += 1; + for (g.entries.items) |*e| if (std.meta.eql(e.key, key)) { + e.tick = g.clock; + return e; + }; + if (g.entries.items.len >= max_entries) { + var oldest: usize = 0; + for (g.entries.items, 0..) |e, i| if (e.tick < g.entries.items[oldest].tick) { + oldest = i; + }; + if (g.entries.items[oldest].exec) |*x| x.deinit(); + _ = g.entries.swapRemove(oldest); + } + try g.entries.append(g.gpa, .{ .key = key, .tick = g.clock }); + return &g.entries.items[g.entries.items.len - 1]; + } + + /// Drops a shape's graph (a rank could not capture it): the shape runs eagerly from now on. + pub fn revoke(g: *Self, e: *Entry) void { + if (e.exec) |*x| x.deinit(); + e.exec = null; + e.state = .failed; + if (g.captured > 0) g.captured -= 1; + } + + /// `body(ctx)` recorded on `stream`: its outputs and the graph (nothing ran), or null when the capture failed. + pub fn record(stream: hip.Stream, ctx: anytype, comptime body: fn (@TypeOf(ctx)) anyerror!Out) !?struct { out: Out, graph: hip.graph.Graph } { + hip.graph.beginCapture(stream, .thread_local) catch return null; + const recorded = body(ctx); + const graph = hip.graph.endCapture(stream) catch return null; + const out = recorded catch |err| { + var g = graph; + g.deinit(); + return if (err == error.OutOfDeviceMemory) err else null; + }; + return .{ .out = out, .graph = graph }; + } + + /// Instantiates a capture that just ended, keeps it with its outputs, and uploads it. + pub fn keep(g: *Self, e: *Entry, graph: hip.graph.Graph, stream: hip.Stream, out: Out) !void { + var tmp = graph; + defer tmp.deinit(); + errdefer e.state = .failed; + var exec = try tmp.instantiate(); + errdefer exec.deinit(); + try exec.upload(stream); + e.exec = exec; + e.out = out; + e.state = .ready; + g.captured += 1; + } + }; +} diff --git a/zig/src/families/qwen3_5/backend/hip/engine/hip_costs.zig b/zig/src/families/qwen3_5/backend/hip/engine/hip_costs.zig new file mode 100644 index 00000000000..c40170a2694 --- /dev/null +++ b/zig/src/families/qwen3_5/backend/hip/engine/hip_costs.zig @@ -0,0 +1,115 @@ +//! The HIP lanes backend's own costs, timed at load on scratch streams: what the depth rule weighs drafts against. + +const std = @import("std"); +const hip = @import("hip"); +const lanes = @import("lanes"); +const Engine = @import("engine.zig").Engine; +const state = @import("../forward/state.zig"); +const draw = @import("draw.zig"); +const mtp = @import("mtp.zig"); + +const Cost = lanes.config.Cost; + +/// Forwards run before the timed ones (the first captures the shape's graph) and the timed reps. +const warm = 3; +const reps = 5; +/// Rows a stream's window holds in the shared timings, and its position (the caches are scratch). +const window = 4; +const at = 16; +/// The total rows timed in shared forwards. +pub const shared_rows = [_]u32{ 2, 4, 8, 12, 16 }; +pub const most_streams = 8; + +pub const Costs = struct { + window: [16]Cost = undefined, + windows: usize = 0, + shared: [shared_rows.len]Cost = undefined, + shareds: usize = 0, + step_ms: f64 = 0.0, +}; + +pub fn nowNs() u64 { + var ts: std.c.timespec = undefined; + _ = std.c.clock_gettime(.MONOTONIC, &ts); + return @as(u64, @intCast(ts.sec)) * 1_000_000_000 + @as(u64, @intCast(ts.nsec)); +} + +const Rig = struct { + gpa: std.mem.Allocator, + e: *Engine, + caches: [most_streams]state.Caches = undefined, + made: usize = 0, + tokens: [64]u32 = @splat(1), + reqs: [64]draw.Request = undefined, + out: [64]u32 = undefined, + + fn deinit(r: *Rig) void { + r.e.drain(); + for (r.caches[0..r.made]) |*c| c.deinit(r.gpa); + } + + /// Mean ms of a verify of `streams` windows of the given widths. + fn time(r: *Rig, widths: []const usize) !f64 { + var rows: [most_streams]Engine.Rows = undefined; + var total: usize = 0; + for (widths, 0..) |w, i| { + rows[i] = .{ .caches = &r.caches[i], .pos = at, .tokens = r.tokens[total..][0..w] }; + for (0..w) |j| r.reqs[total + j] = .{ .sampling = null, .position = at + j + 1 }; + total += w; + } + var spent: u64 = 0; + for (0..warm + reps) |i| { + const t0 = nowNs(); + _ = try r.e.verify(rows[0..widths.len], r.reqs[0..total], &r.out); + if (i >= warm) spent += nowNs() - t0; + } + return @as(f64, @floatFromInt(spent)) / reps / 1e6; + } +}; + +/// Time `h`'s forwards and head on scratch caches of its engine (nothing of a stream is touched). +pub fn measure(gpa: std.mem.Allocator, e: *Engine, head: ?*mtp.Head, out: *Costs) !void { + var r: Rig = .{ .gpa = gpa, .e = e }; + defer r.deinit(); + // the rig runs before any request, on the caches of streams the memory plan holds and none uses yet + const streams = @min(most_streams, e.o.streams); + while (r.made < streams) : (r.made += 1) r.caches[r.made] = try e.newCaches(at + 2 * window * 4); + out.windows = 0; + for (1..out.window.len + 1) |w| { + if (w > e.o.batch_rows) break; + out.window[out.windows] = .{ .width = @intCast(w), .ms = try r.time(&.{w}) }; + out.windows += 1; + } + out.shareds = 0; + for (shared_rows) |total| { + if (total > e.o.batch_rows) break; + var widths: [most_streams]usize = undefined; + var n: usize = 0; + var left: usize = total; + while (left > 0 and n < streams) : (n += 1) { + widths[n] = @min(window, left); + left -= widths[n]; + } + if (left > 0) continue; + out.shared[out.shareds] = .{ .width = total, .ms = try r.time(widths[0..n]) }; + out.shareds += 1; + } + if (head) |hd| out.step_ms = try step(e, hd); +} + +/// One chained head step: a lone chain of the deepest depth, over a scratch row. +fn step(e: *Engine, hd: *mtp.Head) !f64 { + const m = e.model(); + var row = try hip.DeviceBuffer.alloc(&e.driver, m.spec.hidden * m.act.size()); + defer row.free(); + try row.fill8(0); + var held: [mtp.max_depth]u32 = undefined; + var spent: u64 = 0; + for (0..warm + reps) |i| { + var jobs = [_]mtp.Job{.{ .hidden = row.base(), .token = 1, .position = at, .depth = mtp.max_depth, .sampling = null, .stop_under = 0.0, .out = &held }}; + const t0 = nowNs(); + try hd.chains(&e.lib, e.stream, &e.drawer, m, &jobs, e.headGraphs()); + if (i >= warm) spent += nowNs() - t0; + } + return @as(f64, @floatFromInt(spent)) / reps / 1e6 / mtp.max_depth; +} diff --git a/zig/src/families/qwen3_5/backend/hip/engine/hip_lanes.zig b/zig/src/families/qwen3_5/backend/hip/engine/hip_lanes.zig new file mode 100644 index 00000000000..bed4ee92d07 --- /dev/null +++ b/zig/src/families/qwen3_5/backend/hip/engine/hip_lanes.zig @@ -0,0 +1,548 @@ +//! The lane core's HIP backend: every stream its own caches, every round's windows verified in one forward. + +const std = @import("std"); +const hip = @import("hip"); +const lanes = @import("lanes"); +const Engine = @import("engine.zig").Engine; +const state = @import("../forward/state.zig"); +const draw = @import("draw.zig"); +const mtp = @import("mtp.zig"); +const costs = @import("hip_costs.zig"); +const prefix = @import("prefix.zig"); +const hip_prefix = @import("hip_prefix.zig"); +const radix = @import("engine_api").prompt_radix; +const pages = @import("../forward/pages.zig"); +const worker = @import("worker.zig"); + +const be = lanes.backend; + +/// Drawn tokens a handle names, newest last. +const ring = 1024; + +/// Where a prompt pass stands: the row it has reached, and the cuts it still keeps a state at. +const Fill = struct { at: usize, stops: [16]u32, count: usize, next: usize }; + +/// Most chains one draft request runs (the head batches as many as the engine has rows, up to this). +const max_jobs = mtp.max_chains; + +pub const Lane = struct { + caches: state.Caches, + /// The last kept row's final hidden row: the draft head's input. + hidden: hip.DeviceBuffer, + /// Drafts the head holds for the next window. + held: [mtp.max_depth]u32 = undefined, + held_n: usize = 0, + /// Slots written and kept: the next window starts here. + len: usize, + /// The stream's id on every rank. + id: u32 = 0, + /// The prompt pass in progress, a chunk a call (null once it is in). + fill: ?Fill = null, + /// The last verify's slot and rows: kept whole unless keep drops some first. + pending: ?struct { window: usize, rows: usize } = null, + /// A structured reply's prompt row, kept for its masked first draw (null for the others). + first_row: ?[]u16 = null, +}; + +/// The engine this thread's HIP calls go to. +threadlocal var bound: ?*Engine = null; + +pub const Hip = struct { + gpa: std.mem.Allocator, + e: *Engine, + lanes: std.AutoHashMapUnmanaged(*const lanes.Stream, *Lane) = .empty, + head: ?*mtp.Head = null, + drawn: [ring]u32 = undefined, + next: u64 = 0, + /// The streams (and rows) marked kept since the last flush, as the other ranks are told. + marked: std.ArrayList([2]u32) = .empty, + order: []*const lanes.Stream, + /// The pages and linear snapshots kept from prompts for later turns (nothing until `keepPrompts`). + prefix: *hip_prefix.Prefix, + /// Scratch: the pages a match took, and the pages a round copied before writing. + matched: std.ArrayList(u32) = .empty, + copied: std.ArrayList([3]u32) = .empty, + /// Tensor parallelism: the other ranks, which get every step before this rank runs it (`worker.follow`). + link: ?hip.collective.Link = null, + msg: std.ArrayList(u32) = .empty, + /// This engine's forward and head timings, filled by `measure` (none: the rule drafts the deepest it may). + costs: costs.Costs = .{}, + /// Each stream's id on every rank. + ids: std.AutoHashMapUnmanaged(*const lanes.Stream, u32) = .empty, + /// Nanoseconds and calls the backend's verifies, keeps and drafts took; the core's own work is the rest. + spent: [3]u64 = @splat(0), + calls: [3]u64 = @splat(0), + next_id: u32 = 0, + + pub fn init(gpa: std.mem.Allocator, e: *Engine) !*Hip { + const h = try gpa.create(Hip); + errdefer gpa.destroy(h); + const rows = e.o.batch_rows; + h.* = .{ .gpa = gpa, .e = e, .order = undefined, .prefix = try hip_prefix.Prefix.init(gpa, e) }; + errdefer h.prefix.deinit(); + h.order = try gpa.alloc(*const lanes.Stream, rows); + errdefer gpa.free(h.order); + // under tensor parallelism only rank 0 holds the head (whole): drafts only choose the rows every rank verifies + h.head = try mtp.Head.init(gpa, &e.driver, &e.lib, &e.weights, e.model(), @min(rows, max_jobs)); + return h; + } + + /// Time the forwards and the head on scratch caches, for the depth rule; before `facts`, on a lone rank. + pub fn measure(h: *Hip) void { + costs.measure(h.gpa, h.e, h.head, &h.costs) catch |err| { + std.log.warn("lane costs not timed: {s}", .{@errorName(err)}); + h.costs = .{}; + }; + } + + /// Keep up to `slots` snapshots and the pages the rest of `budget` bytes buys in the prefix tree (none: off). + pub fn keepPrompts(h: *Hip, slots: usize, budget: usize) void { + h.prefix.keepPrompts(slots, budget); + } + + /// The prefix tree may hold `max_pages` pages and `snaps` snapshots. + pub fn keepPages(h: *Hip, max_pages: usize, snaps: usize) void { + h.prefix.keepPages(max_pages, snaps); + } + + /// Rank 0 of a tensor-parallel group: every step also goes to the ranks behind `link`. + pub fn withLink(h: *Hip, link: hip.collective.Link) void { + h.link = link; + h.prefix.link = link; + } + + fn send(h: *Hip, words: []const u32) !void { + if (h.link) |l| try l.send(words); + } + + /// A stream's id on every rank. + fn idOf(h: *Hip, s: *const lanes.Stream) !u32 { + const gop = try h.ids.getOrPut(h.gpa, s); + if (!gop.found_existing) { + gop.value_ptr.* = h.next_id; + h.next_id += 1; + } + return gop.value_ptr.*; + } + + fn timed(h: *Hip, which: usize, began: u64) void { + h.spent[which] += costs.nowNs() - began; + h.calls[which] += 1; + } + + pub fn deinit(h: *Hip) void { + const names = [_][]const u8{ "verify", "keep", "draft" }; + for (names, h.spent, h.calls) |name, ns, n| if (n > 0) std.log.info("backend {s}: {d} calls, {d:.0} us each", .{ name, n, @as(f64, @floatFromInt(ns)) / @as(f64, @floatFromInt(n)) / 1e3 }); + if (h.link != null) h.send(&.{@backingInt(worker.Op.stop)}) catch {}; + h.ids.deinit(h.gpa); + h.marked.deinit(h.gpa); + h.msg.deinit(h.gpa); + h.e.stream.synchronize() catch {}; + h.matched.deinit(h.gpa); + h.copied.deinit(h.gpa); + var it = h.lanes.valueIterator(); + while (it.next()) |l| h.free(l.*); + if (h.head) |hd| { + if (hd.graphs.captured > 0) std.log.info("head graphs: {d} captured, {d} of {d} batches replayed", .{ hd.graphs.captured, hd.graphs.replayed, hd.graphs.rounds }); + hd.deinit(); + } + h.lanes.deinit(h.gpa); + h.prefix.deinit(); + h.gpa.free(h.order); + h.gpa.destroy(h); + } + + pub fn backend(h: *Hip) be.Backend { + return .{ .ptr = h, .vtable = &.{ + .prefill = prefillFn, + .prefill_step = prefillStepFn, + .first = firstFn, + .first_masked = firstMaskedFn, + .held = heldTokensFn, + .queue = queueFn, + .read = readFn, + .verify = verifyFn, + .keep = keepFn, + .draft = draftFn, + .tree = heldFn, + .release = releaseFn, + } }; + } + + /// Rows a window holds: every width keeps a row's bits (the window forward), drafts come from the core. + pub const max_window = 16; + + /// The facts the round loop reads at setup: shared rounds of exact windows, and the MTP head's batched chains. + pub fn facts(h: *const Hip) lanes.Model { + const drafting = h.head != null and h.e.o.policy.mtp.drafts > 0; + // plain rounds compete with drafted ones once the forwards are timed + const plain_guard = drafting and h.costs.windows > 0; + return .{ + .exact_width = max_window, + .gpu_tokens = false, + .mtp = drafting, + .speculate = drafting, + .speculate_early = false, + .drafts = @min(mtp.max_depth, h.e.o.policy.mtp.drafts), + .hidden_rows = true, + .batch_rows = @intCast(h.e.o.batch_rows), + .max_streams = @intCast(h.e.o.batch_rows), + .draft_streams = drafting, + .plain_guard = plain_guard, + .window_costs = h.costs.window[0..h.costs.windows], + .shared_costs = h.costs.shared[0..h.costs.shareds], + .mtp_step_ms = h.costs.step_ms, + }; + } + + fn free(h: *Hip, l: *Lane) void { + h.e.drain(); + l.caches.deinit(h.gpa); + l.hidden.free(); + if (l.first_row) |row| h.gpa.free(row); + h.gpa.destroy(l); + } + + /// Whether a stream past its prompt holds a lane: a prompt's chunk then holds its round back. + fn decoding(h: *const Hip) bool { + var it = h.lanes.valueIterator(); + while (it.next()) |l| if (l.*.fill == null) return true; + return false; + } + + /// The backend behind `ptr`, the calling thread bound to its GPU (the lane thread did not open it). + fn of(ptr: *anyopaque) *Hip { + const h: *Hip = @ptrCast(@alignCast(ptr)); + if (bound != h.e) { + h.e.ctx.makeCurrent() catch |err| std.log.err("hipSetDevice on the lane thread: {s}", .{@errorName(err)}); + bound = h.e; + } + return h; + } + + fn take(h: *Hip, token: u32) u64 { + const at = h.next; + h.drawn[at % ring] = token; + h.next += 1; + return at; + } + + /// A verify the round loop did not trim keeps every row (the core keeps only on drops). + fn settle(h: *Hip, lane: *Lane) !void { + const p = lane.pending orelse return; + try h.mark(lane, p.rows); + } + + /// Marks the pending window's first `rows` rows kept (the stream's length moves on); `flush` lands them. + fn mark(h: *Hip, lane: *Lane, rows: usize) !void { + const p = lane.pending.?; + try h.marked.append(h.gpa, .{ lane.id, @intCast(rows) }); + h.e.keep(p.window, rows); + lane.len += rows; + lane.pending = null; + } + + /// Lands the marked keeps in one launch: linear states after the kept rows, the last kept final row for the head. + fn flush(h: *Hip) !void { + if (h.marked.items.len == 0) return; + if (h.link != null) { + h.msg.clearRetainingCapacity(); + try h.msg.appendSlice(h.gpa, &.{ @backingInt(worker.Op.keep), @intCast(h.marked.items.len) }); + for (h.marked.items) |k| try h.msg.appendSlice(h.gpa, &k); + try h.send(h.msg.items); + } + h.marked.clearRetainingCapacity(); + try h.e.flush(); + } + + fn sampling(s: *const lanes.Stream) ?lanes.Sampling { + return s.sampling; + } + + /// Pages for the stream's positions up to `upto`, each its own to write: the other ranks are told what changed. + fn ensure(h: *Hip, lane: *Lane, upto: usize) !void { + const before = lane.caches.table.items.len; + const grown = try lane.caches.grow(h.gpa, upto); + if (grown.len > 0) try h.prefix.sendPages(lane.id, before, grown); + h.copied.clearRetainingCapacity(); + try lane.caches.writable(&h.copied, h.gpa, lane.len, upto, h.e.stream.handle); + for (h.copied.items) |c| { + try h.send(&.{ @backingInt(worker.Op.copy), c[1], c[2] }); + try h.prefix.sendPages(lane.id, c[0], &.{c[2]}); + } + } + + /// The whole prompt pass, chunk by chunk (a driver of its own, with no rounds between). + fn prefillFn(ptr: *anyopaque, s: *lanes.Stream) anyerror!void { + while (!try prefillStepFn(ptr, s)) {} + } + + /// The stream's lane and prompt pass begun: its pages, the resume from a snapshot, the cuts, the other ranks told. + fn begin(h: *Hip, s: *lanes.Stream) !*Lane { + const prompt = s.prompt(); + if (prompt.len == 0 or prompt.len + s.max_new + 1 > h.e.o.capacity) return error.PromptTooLong; + const gop = try h.lanes.getOrPut(h.gpa, s); + if (gop.found_existing) h.free(gop.value_ptr.*); + errdefer h.lanes.removeByPtr(gop.key_ptr); + const total = prompt.len + s.max_new + max_window + 1; + const lane = blk: { + var caches = try h.e.emptyCaches(total); + errdefer caches.deinit(h.gpa); + var hidden = try hip.DeviceBuffer.alloc(&h.e.driver, h.e.model().spec.hidden * h.e.model().act.size()); + errdefer hidden.free(); + try caches.setHidden(hidden.base()); + const l = try h.gpa.create(Lane); + l.* = .{ .caches = caches, .hidden = hidden, .len = prompt.len }; + break :blk l; + }; + errdefer h.free(lane); + gop.value_ptr.* = lane; + lane.id = try h.idOf(s); + // a request resumes from the deepest shared snapshot and keeps its own marks, drafted or serial alike + var owner: hip_prefix.Owner = .{ .caches = &lane.caches, .id = lane.id }; + h.matched.clearRetainingCapacity(); + h.prefix.restored = worker.no_snapshot; + const plan = try h.prefix.begin(prompt, s.history_len, s.shared_prefixes, &owner, &h.matched); + defer h.gpa.free(plan.marks); + errdefer for (h.matched.items) |id| h.e.pool.release(id); + const at: usize = plan.from; + const adopted = h.matched.items.len; + try lane.caches.set(h.gpa, 0, h.matched.items); + h.matched.clearRetainingCapacity(); + // pages for the whole request are promised now, so no round runs out of them + const need = pages.pagesFor(lane.caches.total) - adopted; + if (!h.prefix.store.reclaim(need)) return error.OutOfPages; + lane.caches.promised = need; + h.e.pool.ids.reserved += need; + _ = try lane.caches.grow(h.gpa, prompt.len); + s.cached = @intCast(at); + var fill: Fill = .{ .at = at, .stops = undefined, .count = @min(plan.marks.len, 16), .next = 0 }; + @memcpy(fill.stops[0..fill.count], plan.marks[0..fill.count]); + lane.fill = fill; + if (h.link != null) { + // the other ranks get the stream's pages and where it resumed and cuts + h.msg.clearRetainingCapacity(); + const held = lane.caches.table.items; + try h.msg.appendSlice(h.gpa, &.{ @backingInt(worker.Op.prefill), lane.id, @intCast(lane.caches.total), @intCast(prompt.len), @intCast(at), @intCast(fill.count), h.prefix.restored, @intCast(held.len) }); + try h.msg.appendSlice(h.gpa, held); + try h.msg.appendSlice(h.gpa, fill.stops[0..fill.count]); + try h.msg.appendSlice(h.gpa, prompt); + try h.send(h.msg.items); + } + return lane; + } + + /// One chunk of the prompt pass, ending on the next cut or the prompt's end; the last draws the first token. + fn prefillStepFn(ptr: *anyopaque, s: *lanes.Stream) anyerror!bool { + const h = of(ptr); + if (s.isCancelled()) return error.Cancelled; + const lane = if (h.lanes.get(s)) |l| (if (l.fill != null) l else try h.begin(s)) else try h.begin(s); + const prompt = s.prompt(); + const f = &lane.fill.?; + const limit: usize = if (f.next < f.count) f.stops[f.next] else prompt.len; + // a prompt cut anywhere on 64 rows gives the same bits; streams decoding between chunks wait less on short ones + const to = prefix.chunkEnd(f.at, limit, if (h.decoding()) h.e.o.policy.fill_rows else prefix.chunk); + if (h.link != null) try h.send(&.{ @backingInt(worker.Op.fill), lane.id, @intCast(to) }); + if (to == prompt.len) { + // a structured reply keeps the prompt's last row: its first token is drawn again under the grammar + if (s.grammar != null and lane.first_row == null) lane.first_row = try h.gpa.alloc(u16, h.e.drawer.vocab); + const keep = if (s.grammar != null) lane.first_row else null; + _ = h.take(try h.e.prefill(&lane.caches, prompt, f.at, lane.hidden, .{ .sampling = sampling(s), .position = prompt.len, .keep = keep }, null)); + lane.fill = null; + return true; + } + try h.e.advance(&lane.caches, prompt, f.at, to, null); + f.at = to; + if (f.next < f.count and to == f.stops[f.next]) { + var owner: hip_prefix.Owner = .{ .caches = &lane.caches, .id = lane.id }; + h.prefix.keep(&owner, prompt, to) catch |err| std.log.warn("prefix not kept: {s}", .{@errorName(err)}); + f.next += 1; + } + return false; + } + + fn firstFn(ptr: *anyopaque, s: *lanes.Stream, position: u64) anyerror!u64 { + const h = of(ptr); + if (position != s.prompt_len) { + std.log.err("first draw at {d}, the prompt has {d} tokens", .{ position, s.prompt_len }); + return error.PositionMismatch; + } + return h.next - 1; + } + + /// The first token among the grammar's allowed ones, from the prompt row the pass kept. + fn firstMaskedFn(ptr: *anyopaque, s: *lanes.Stream, position: u64, bits: []const u32) anyerror!u64 { + const h = of(ptr); + if (position != s.prompt_len) return error.PositionMismatch; + const lane = h.lanes.get(s) orelse return error.UnknownStream; + const kept = lane.first_row orelse return error.StructuresUnsupported; + const row = try h.gpa.dupe(u16, kept); + defer h.gpa.free(row); + return h.take(try h.e.drawer.drawHost(row, .{ .sampling = sampling(s), .position = position, .mask = bits })); + } + + /// The drafts the head holds for the stream, as host tokens (a grammar walks them). + fn heldTokensFn(ptr: *anyopaque, s: *lanes.Stream, out: []u32) anyerror!void { + const lane = of(ptr).lanes.get(s) orelse return error.UnknownStream; + if (out.len > lane.held_n) return error.NoHeldDrafts; + @memcpy(out, lane.held[0..out.len]); + } + + fn queueFn(ptr: *anyopaque, s: *lanes.Stream, feed: be.Feed, position: u64) anyerror!u64 { + _ = ptr; + _ = s; + _ = feed; + _ = position; + return error.NotPipelined; + } + + fn readFn(ptr: *anyopaque, handle: u64) anyerror!u32 { + const h = of(ptr); + if (handle >= h.next or h.next - handle > ring) return error.NoSuchToken; + return h.drawn[handle % ring]; + } + + /// Each stream's window from its kept length: the pending token, then the host's drafts; one forward for all. + fn verifyFn(ptr: *anyopaque, windows: []const be.Window, out: []be.Verified) anyerror!void { + const h = of(ptr); + const began = costs.nowNs(); + defer h.timed(0, began); + if (windows.len > h.order.len) return error.WindowTooWide; + // windows the round loop did not trim keep every row before this round's plan replaces theirs + for (windows) |w| try h.settle(h.lanes.get(w.stream) orelse return error.UnknownStream); + try h.flush(); + for (windows) |w| { + const lane = h.lanes.get(w.stream).?; + try h.ensure(lane, lane.len + w.rows()); + } + var rows: [64]Engine.Rows = undefined; + var tokens: [64][16]u32 = undefined; + if (windows.len > rows.len) return error.WindowTooWide; + for (windows, 0..) |w, i| { + if (w.parents != null) return error.TreesNotBuilt; + const lane = h.lanes.get(w.stream) orelse return error.UnknownStream; + if (w.held > lane.held_n or (w.held > 0 and w.tokens.len > 0)) return error.NoHeldDrafts; + const n = w.rows(); + if (n > tokens[i].len) return error.WindowTooWide; + for (w.positions, 0..) |p, r| if (p != lane.len + 1 + r) { + std.log.err("row {d} keyed at {d}, the stream holds {d} slots", .{ r, p, lane.len }); + return error.PositionMismatch; + }; + tokens[i][0] = w.pending; + if (w.held > 0) @memcpy(tokens[i][1..n], lane.held[0..w.held]) else @memcpy(tokens[i][1..n], w.tokens); + rows[i] = .{ .caches = &lane.caches, .pos = lane.len, .tokens = tokens[i][0..n] }; + h.order[i] = w.stream; + } + var reqs: [256]draw.Request = undefined; + var drawn: [256]u32 = undefined; + var total: usize = 0; + for (windows) |w| { + if (total + w.positions.len > reqs.len) return error.WindowTooWide; + // structured output: each row's allowed bits, rows x words + const words = if (w.masks.len > 0) w.masks.len / w.positions.len else 0; + for (w.positions, 0..) |p, r| { + reqs[total] = .{ .sampling = sampling(w.stream), .position = p, .mask = w.masks[r * words ..][0..words] }; + total += 1; + } + } + // the graph choice is rank 0's, and goes with the round + const pick = try h.e.choose(rows[0..windows.len], null); + if (h.link != null) { + h.msg.clearRetainingCapacity(); + try h.msg.appendSlice(h.gpa, &.{ @backingInt(worker.Op.verify), @backingInt(pick), @intCast(windows.len) }); + for (windows, rows[0..windows.len]) |w, r| { + try h.msg.appendSlice(h.gpa, &.{ h.lanes.get(w.stream).?.id, @intCast(r.tokens.len) }); + try h.msg.appendSlice(h.gpa, r.tokens); + } + try h.send(h.msg.items); + } + _ = try h.e.verify(rows[0..windows.len], reqs[0..total], &drawn); + var at: usize = 0; + for (windows, out, 0..) |w, *o, i| { + @memcpy(o.sampled, drawn[at..][0..o.sampled.len]); + const lane = h.lanes.get(w.stream).?; + @memcpy(o.drafts, if (w.held > 0) lane.held[0..w.held] else w.tokens); + lane.held_n = 0; + lane.pending = .{ .window = i, .rows = w.rows() }; + at += w.rows(); + } + } + + /// Keep each stream's accepted prefix: lengths, and the linear states of its last kept row. + fn keepFn(ptr: *anyopaque, windows: []const be.Window, paths: []const []const u32) anyerror!void { + const h = of(ptr); + const began = costs.nowNs(); + defer h.timed(1, began); + for (windows, paths) |w, path| { + const lane = h.lanes.get(w.stream) orelse return error.UnknownStream; + for (path, 0..) |r, j| if (r != j) return error.TreesNotBuilt; + // the draft request of the same round may have kept these rows already + if (lane.pending == null) continue; + try h.mark(lane, path.len); + } + try h.flush(); + } + + /// The head drafts `depth` from each stream's last kept row and its pending token, one head forward a step for all. + fn draftFn(ptr: *anyopaque, requests: []const be.DraftRequest) anyerror!void { + const h = of(ptr); + const began = costs.nowNs(); + defer h.timed(2, began); + const head = h.head orelse return error.NoDraftHead; + const m = h.e.model(); + var jobs: [max_jobs]mtp.Job = undefined; + var chained: [max_jobs]*Lane = undefined; + var n: usize = 0; + // a shared round asks for drafts before its keep: the request names the kept rows + for (requests) |r| { + const lane = h.lanes.get(r.stream) orelse return error.UnknownStream; + if (lane.pending != null) { + if (r.rows) |kept| try h.mark(lane, kept.len) else try h.settle(lane); + } + } + try h.flush(); + for (requests) |r| { + const lane = h.lanes.get(r.stream) orelse return error.UnknownStream; + if (r.position != lane.len + 1) { + std.log.err("draft for {s} at {d}, the stream holds {d} slots (rows {any}, depth {d})", .{ r.stream.id, r.position, lane.len, r.rows, r.depth }); + return error.PositionMismatch; + } + const token: u32 = if (r.rows != null) r.follow[r.follow.len - 1] else switch (r.first orelse return error.NoFirstToken) { + .handle => |at| h.drawn[at % ring], + .value => |v| v, + }; + lane.held_n = 0; + if (r.depth == 0) continue; + if (n == max_jobs) return error.WindowTooWide; + // a chain ends after a draft the head gives under the confidence; the first drafts run whole + const stop_under: f64 = if (r.rows != null) h.e.o.policy.mtp.confidence else 0.0; + jobs[n] = .{ .hidden = lane.hidden.base(), .token = token, .position = lane.len, .depth = r.depth, .sampling = sampling(r.stream), .stop_under = stop_under, .out = &lane.held }; + chained[n] = lane; + n += 1; + } + try head.chains(&h.e.lib, h.e.stream, &h.e.drawer, m, jobs[0..n], h.e.headGraphs()); + var k: usize = 0; + for (requests) |r| { + if (r.depth == 0) continue; + const lane = chained[k]; + lane.held_n = jobs[k].kept; + k += 1; + if (lane.held_n > r.depth or (lane.held_n < r.depth and r.rows == null)) return error.ShortChain; + } + } + + /// The drafts the head holds for the stream after its last chain: fewer than asked when a draft cut it. + fn heldFn(ptr: *anyopaque, s: *lanes.Stream, _: std.mem.Allocator) anyerror!?lanes.stream.Held { + const lane = of(ptr).lanes.get(s) orelse return error.UnknownStream; + return .{ .count = @intCast(lane.held_n) }; + } + + fn releaseFn(ptr: *anyopaque, s: *lanes.Stream) void { + const h = of(ptr); + const kv = h.lanes.fetchRemove(s) orelse return; + if (h.link != null) h.send(&.{ @backingInt(worker.Op.release), kv.value.id }) catch {}; + _ = h.ids.remove(s); + h.e.stream.synchronize() catch {}; + h.free(kv.value); + } +}; diff --git a/zig/src/families/qwen3_5/backend/hip/engine/hip_prefix.zig b/zig/src/families/qwen3_5/backend/hip/engine/hip_prefix.zig new file mode 100644 index 00000000000..06dfcd1699c --- /dev/null +++ b/zig/src/families/qwen3_5/backend/hip/engine/hip_prefix.zig @@ -0,0 +1,153 @@ +//! The prompt cache's HIP side: pages and snapshots for core/prompt_radix.zig; rank 0 decides, other ranks apply. + +const std = @import("std"); +const hip = @import("hip"); +const radix = @import("engine_api").prompt_radix; +const memory = @import("memory.zig"); +const worker = @import("worker.zig"); +const state = @import("../forward/state.zig"); +const pages = @import("../forward/pages.zig"); +const Engine = @import("engine.zig").Engine; +const Allocator = std.mem.Allocator; + +/// What a stream gives the prompt cache: its caches and the id the other ranks know it by. +pub const Owner = struct { caches: *state.Caches, id: u32 }; + +pub const Prefix = struct { + gpa: Allocator, + e: *Engine, + store: radix.Store, + snaps: state.Snapshots, + /// Snapshot slots in use. + used: std.ArrayList(bool) = .empty, + /// The other ranks, when this is rank 0 of a group. + link: ?hip.collective.Link = null, + msg: std.ArrayList(u32) = .empty, + /// The slot the last restore copied from (reset as a pass begins): the message that begins the pass names it. + restored: u32 = worker.no_snapshot, + + pub fn init(gpa: Allocator, e: *Engine) !*Prefix { + const p = try gpa.create(Prefix); + errdefer gpa.destroy(p); + const rules: radix.Rules = .{ .page = pages.tokens, .min_gap = @import("prefix.zig").min_gap, .min_prompt = 0, .tail = true }; + p.* = .{ .gpa = gpa, .e = e, .store = try radix.Store.init(gpa, .{ .ptr = p, .vtable = &family }, .{ .ptr = &e.pool, .vtable = &pool_pages, .bytes = e.pool.pageBytes() }, rules), .snaps = state.Snapshots.init(gpa, &e.driver) }; + return p; + } + + pub fn deinit(p: *Prefix) void { + p.store.deinit(); + p.snaps.deinit(); + p.used.deinit(p.gpa); + p.msg.deinit(p.gpa); + p.gpa.destroy(p); + } + + /// Keep up to `slots` snapshots and the pages the rest of `budget` bytes buys, a budget the memory plan granted. + pub fn keepPrompts(p: *Prefix, slots: usize, budget: usize) void { + const m = p.e.model(); + const room = memory.cache(m.spec, m.act.size(), budget, slots); + p.keepPages(@min(room.pages, p.e.pool.count), room.snaps); + } + + /// The tree may hold `max_pages` pages and `snaps` snapshots. + pub fn keepPages(p: *Prefix, max_pages: usize, snaps: usize) void { + p.store.limit(.{ .pages = max_pages, .snaps = snaps }); + if (p.store.tree.snaps == 0) p.snaps.clear(); + } + + pub fn send(p: *Prefix, words: []const u32) !void { + if (p.link) |l| try l.send(words); + } + + /// Tells the other ranks that the stream's pages from page `first` on are `ids`. + pub fn sendPages(p: *Prefix, id: u32, first: usize, ids: []const u32) !void { + if (p.link == null) return; + p.msg.clearRetainingCapacity(); + try p.msg.appendSlice(p.gpa, &.{ @backingInt(worker.Op.pages), id, @intCast(first), @intCast(ids.len) }); + try p.msg.appendSlice(p.gpa, ids); + try p.send(p.msg.items); + } + + /// Before a prompt pass: the longest resumable state restored into the stream, its pages in `adopt`, the marks. + pub fn begin(p: *Prefix, prompt: []const u32, history_len: u32, shared: []const u32, owner: *Owner, adopt: *std.ArrayList(u32)) !radix.Plan { + return p.store.begin(p.gpa, prompt, history_len, shared, owner, adopt); + } + + /// At `at` the tree takes the pages it lacks and the linear state; the stream swaps in the pages the tree had. + pub fn keep(p: *Prefix, owner: *Owner, prompt: []const u32, at: usize) !void { + if (!p.store.on()) return; + const n = at / pages.tokens; + const path = try p.gpa.alloc(u32, n); + defer p.gpa.free(path); + const caches = owner.caches; + const kept = p.store.keep(prompt, @intCast(at), owner, caches.table.items[0..n], path); + const own = path[0..kept.shared]; + if (!std.mem.eql(u32, own, caches.table.items[0..kept.shared])) { + for (own) |id| p.e.pool.retain(id); + try caches.set(p.gpa, 0, own); + try p.sendPages(owner.id, 0, own); + } + } + + fn slotOf(saved: radix.Saved) u32 { + return @intCast(@intFromPtr(saved) - 1); + } + + fn of(ptr: *anyopaque) *Prefix { + return @ptrCast(@alignCast(ptr)); + } + + fn snapBytes(ptr: *anyopaque, _: u32) u64 { + return memory.linearBytes(of(ptr).e.model().spec); + } + + fn save(ptr: *anyopaque, owner: ?*anyopaque, _: u32) anyerror!radix.Saved { + const p = of(ptr); + const o: *Owner = @ptrCast(@alignCast(owner.?)); + const slot: u32 = for (p.used.items, 0..) |u, i| { + if (!u) break @intCast(i); + } else blk: { + try p.used.append(p.gpa, false); + break :blk @intCast(p.used.items.len - 1); + }; + try p.snaps.take(slot, o.caches, p.e.stream.handle); + p.used.items[slot] = true; + try p.send(&.{ @backingInt(worker.Op.snap), o.id, slot }); + return @ptrFromInt(@as(usize, slot) + 1); + } + + fn restore(ptr: *anyopaque, owner: ?*anyopaque, saved: radix.Saved) anyerror!void { + const p = of(ptr); + const o: *Owner = @ptrCast(@alignCast(owner.?)); + try p.snaps.put(slotOf(saved), o.caches, p.e.stream.handle); + p.restored = slotOf(saved); + } + + fn dropSaved(ptr: *anyopaque, saved: radix.Saved) void { + of(ptr).used.items[slotOf(saved)] = false; + } + + const family: radix.Snapshots.VTable = .{ .bytes = snapBytes, .save = save, .restore = restore, .drop = dropSaved }; + + fn pool(ptr: *anyopaque) *pages.Pool { + return @ptrCast(@alignCast(ptr)); + } + + fn retain(ptr: *anyopaque, id: u32) void { + pool(ptr).retain(id); + } + + fn release(ptr: *anyopaque, id: u32) void { + pool(ptr).release(id); + } + + fn holders(ptr: *anyopaque, id: u32) u32 { + return pool(ptr).ids.refs[id]; + } + + fn available(ptr: *anyopaque) usize { + return pool(ptr).ids.available(); + } + + const pool_pages: radix.Pages.VTable = .{ .retain = retain, .release = release, .holders = holders, .available = available }; +}; diff --git a/zig/src/families/qwen3_5/backend/hip/engine/memory.zig b/zig/src/families/qwen3_5/backend/hip/engine/memory.zig new file mode 100644 index 00000000000..3b24a8060d9 --- /dev/null +++ b/zig/src/families/qwen3_5/backend/hip/engine/memory.zig @@ -0,0 +1,36 @@ +//! Bytes of a stream's state and of the prompt cache: pages of keys and values, and the linear layers' state. + +const config = @import("../../../weights/config.zig"); +const pages = @import("../forward/pages.zig"); + +/// Bytes of one page of the pool: the keys and values of 64 positions in every attention layer. +pub fn pageBytes(s: config.Spec, act_bytes: usize) usize { + var full: usize = 0; + for (0..s.n_layers) |i| full += @intFromBool(s.full(i)); + return full * 2 * s.kv_heads * s.head_dim * act_bytes * pages.tokens; +} + +/// One stream's (or one snapshot's) linear state: the conv window and the recurrent state of every linear layer. +pub fn linearBytes(s: config.Spec) usize { + var full: usize = 0; + for (0..s.n_layers) |i| full += @intFromBool(s.full(i)); + const conv = (s.keyWidth() * 2 + s.valueWidth()) * (s.conv - 1) * 4; + const recurrent = s.value_heads * s.value_dim * s.key_dim * 4; + return (s.n_layers - full) * (conv + recurrent); +} + +/// Bytes one stream's caches hold at `tokens` positions: attention keys and values plus the linear layers' state. +pub fn stateBytes(s: config.Spec, act_bytes: usize, tokens: usize) usize { + var full: usize = 0; + for (0..s.n_layers) |i| full += @intFromBool(s.full(i)); + return full * 2 * s.kv_heads * s.head_dim * act_bytes * tokens + linearBytes(s); +} + +/// What `budget` bytes of prompt cache hold: at most `slots` snapshots, up to half of it, and pages for the rest. +pub const Cache = struct { pages: usize, snaps: usize }; + +pub fn cache(s: config.Spec, act_bytes: usize, budget: usize, slots: usize) Cache { + const snap = @max(linearBytes(s), 1); + const snaps = @min(slots, budget / 2 / snap); + return .{ .pages = (budget - snaps * snap) / @max(pageBytes(s, act_bytes), 1), .snaps = snaps }; +} diff --git a/zig/src/families/qwen3_5/backend/hip/engine/mtp.zig b/zig/src/families/qwen3_5/backend/hip/engine/mtp.zig new file mode 100644 index 00000000000..605d9bfaa84 --- /dev/null +++ b/zig/src/families/qwen3_5/backend/hip/engine/mtp.zig @@ -0,0 +1,375 @@ +//! The MTP head drafting chains: one head forward a step over a row each; a round costs one chain's steps, one sync. + +const std = @import("std"); +const hip = @import("hip"); +const lanes = @import("lanes"); +const view = @import("../model/view.zig"); +const weights = @import("../model/weights.zig"); +const bridge = @import("../model/bridge.zig"); +const fwd = @import("../forward/forward.zig"); +const draw = @import("draw.zig"); +const plan = @import("../forward/plan.zig"); +const graph_cache = @import("graph_cache.zig"); + +const pops = hip.plan_ops; +const Ops = hip.ops.Ops; +const Tensor = hip.ops.Tensor; + +/// Most drafts a chain (the Python engine's depth). +pub const max_depth = 3; + +/// One stream's chain: its last kept final row, the token after it and its slot, the drafts asked for and their draw. +pub const Job = struct { + hidden: u64, + token: u32, + position: usize, + depth: usize, + sampling: ?lanes.Sampling, + stop_under: f64, + out: []u32, + kept: usize = 0, +}; + +/// What a greedy batch's launches depend on: its chain bucket, drafts per chain, whether the confidence cut runs. +const ChainKey = struct { rows: u32, most: u32, cut: bool }; + +/// A greedy chain reads the head over the first ids of the vocabulary alone (the common tokens): a draft only guesses. +const draft_vocab = 65536; + +/// Most chains one batch runs; a head serving `rows` rows a round holds caches for this many at most. +pub const max_chains = 64; + +pub const Head = struct { + gpa: std.mem.Allocator, + d: *const hip.Runtime, + w: *const weights.MtpHead, + heads: usize, + kv_heads: usize, + mlp: ?view.Mlp, + logits_head: view.Projection, + /// The same weights over the first `draft_vocab` ids. + draft_head: view.Projection, + /// Most chains a batch runs together; each has its own cache of `max_depth + 1` slots. + cap: usize, + cache_bytes: usize, + k: hip.DeviceBuffer, + v: hip.DeviceBuffer, + arena: hip.Arena, + /// The chains' last kept final rows gathered, (cap, hidden). + rows: hip.DeviceBuffer, + /// A row of zeros: the padding chains' input. + zero: hip.DeviceBuffer, + scalars: hip.HostBuffer, // `Layout`'s words, pinned + scalars_dev: hip.DeviceBuffer, + last: u64 = 0, // the last step's final rows, the next step's hidden input + /// Greedy batches captured by shape: the head's launches over the scalars alone, replayed. + graphs: graph_cache.Cache(ChainKey, void), + + /// The head of `m` with no device memory yet, or null when the checkpoint has none: what `deviceBytes` counts. + fn describe(gpa: std.mem.Allocator, d: *const hip.Runtime, m: *const weights.Model, model: *const view.Model, cap: usize) !?Head { + const w = if (m.mtp) |*x| x else return null; + const s = m.spec; + const qa = try bridge.projection(w.q); + const ka = try bridge.projection(w.k); + const kv_heads = ka.n / s.head_dim; + const full = if (w.head) |hp| try bridge.projection(hp) else model.head; + var narrow = full; + narrow.n = @min(full.n, draft_vocab); + const none: hip.DeviceBuffer = .{ .r = d, .ptr = null, .len = 0 }; + return .{ + .gpa = gpa, + .d = d, + .w = w, + .heads = qa.n / s.head_dim / @as(usize, if (w.gated) 2 else 1), + .kv_heads = kv_heads, + .mlp = if (w.mlp) |x| try bridge.mlpView(x, false) else null, + .logits_head = full, + .draft_head = narrow, + .cap = cap, + .cache_bytes = kv_heads * (max_depth + 1) * s.head_dim * model.act.size(), + .k = none, + .v = none, + .arena = hip.Arena.counting(), + .rows = none, + .zero = none, + .graphs = graph_cache.Cache(ChainKey, void).init(gpa), + .scalars = undefined, + .scalars_dev = none, + }; + } + + /// Device bytes the head of `m` holds for `cap` chains (0 without one): caches, rows, scalars and its arena. + pub fn deviceBytes(gpa: std.mem.Allocator, d: *const hip.Runtime, lib: *const hip.Launcher, m: *const weights.Model, model: *const view.Model, cap: usize) !usize { + var h = (try describe(gpa, d, m, model, cap)) orelse return 0; + defer h.graphs.deinit(); + const row = m.spec.hidden * model.act.size(); + return 2 * h.cache_bytes * cap + cap * row + row + h.layout().total + try h.scratch(lib, model); + } + + /// The head of `m`, or null when the checkpoint has none; `cap` chains at most run in one batch. + pub fn init(gpa: std.mem.Allocator, d: *const hip.Runtime, lib: *const hip.Launcher, m: *const weights.Model, model: *const view.Model, cap: usize) !?*Head { + const described = (try describe(gpa, d, m, model, cap)) orelse return null; + const s = m.spec; + const h = try gpa.create(Head); + errdefer gpa.destroy(h); + h.* = described; + errdefer h.graphs.deinit(); + h.k = try hip.DeviceBuffer.alloc(d, h.cache_bytes * cap); + errdefer h.k.free(); + h.v = try hip.DeviceBuffer.alloc(d, h.cache_bytes * cap); + errdefer h.v.free(); + h.rows = try hip.DeviceBuffer.alloc(d, cap * s.hidden * model.act.size()); + errdefer h.rows.free(); + h.zero = try hip.DeviceBuffer.alloc(d, s.hidden * model.act.size()); + errdefer h.zero.free(); + try h.zero.fill8(0); + h.scalars = try hip.HostBuffer.alloc(d, h.layout().total); + errdefer h.scalars.free(); + h.scalars_dev = try hip.DeviceBuffer.alloc(d, h.layout().total); + errdefer h.scalars_dev.free(); + h.arena = try hip.Arena.init(d, try h.scratch(lib, model)); + return h; + } + + /// The arena a batch of `cap` chains takes at full depth, greedy or sampled, counted on the counting stream. + fn scratch(h: *Head, lib: *const hip.Launcher, m: *const view.Model) !usize { + var most: usize = 0; + for ([_]view.Projection{ h.draft_head, h.logits_head }) |head| { + var arena = hip.Arena.counting(); + const o: Ops = .{ .l = lib, .bf16 = m.act == .bf16, .stream = hip.counting, .arena = &arena }; + try h.steps(o, m, head, h.cap, max_depth, true); + most = @max(most, arena.peak); + } + return most; + } + + pub fn deinit(h: *Head) void { + h.graphs.deinit(); + h.scalars_dev.free(); + h.scalars.free(); + h.zero.free(); + h.rows.free(); + h.arena.deinit(); + h.v.free(); + h.k.free(); + h.gpa.destroy(h); + } + + /// Scalar byte offsets: uploads (tokens, slots, positions, input row addresses), then downloads (drafts, probs). + const Layout = struct { slots: usize, pos: usize, ptrs: usize, drafts: usize, probs: usize, total: usize }; + + fn layout(h: *const Head) Layout { + const slots = 4 * h.cap; + const pos = slots + 4 * max_depth; + const ptrs = std.mem.alignForward(usize, pos + 4 * max_depth * h.cap, 8); + const drafts = ptrs + 8 * h.cap; + const probs = drafts + 4 * max_depth * h.cap; + return .{ .slots = slots, .pos = pos, .ptrs = ptrs, .drafts = drafts, .probs = probs, .total = probs + 4 * max_depth * h.cap }; + } + + /// A projection of the head in whichever format: an unquantized fp32 weight an MTP fc may keep, or a quantized one. + fn project(o: Ops, p: weights.Projection, x: Tensor, rows: usize) !Tensor { + return o.project(x, try bridge.projection(p), rows, false); + } + + /// Every job's chain, `cap` at a time, up to `depth` drafts each, cut after a draft under `stop_under` (0: never). + pub fn chains(h: *Head, lib: *const hip.Launcher, stream: hip.Stream, drawer: *draw.Drawer, m: *const view.Model, jobs: []Job, graphs: bool) !void { + var at: usize = 0; + while (at < jobs.len) : (at += h.cap) try h.batch(lib, stream, drawer, m, jobs[at..][0..@min(h.cap, jobs.len - at)], graphs); + } + + fn batch(h: *Head, lib: *const hip.Launcher, stream: hip.Stream, drawer: *draw.Drawer, m: *const view.Model, jobs: []Job, graphs: bool) !void { + const o: Ops = .{ .l = lib, .bf16 = m.act == .bf16, .stream = stream.handle, .arena = &h.arena }; + h.arena.reset(); + const rows = jobs.len; + const at = h.layout(); + const width = m.spec.hidden * m.act.size(); + var most: usize = 0; + var greedy = true; + var cut = false; + for (jobs) |j| { + most = @max(most, @min(j.depth, max_depth, j.out.len)); + if (j.sampling) |s| greedy = greedy and s.temperature <= 0.0; + cut = cut or j.stop_under > 0.0; + } + const sc = h.scalars.slice(i32); + const srcs = h.scalars.slice(u64); + // greedy chains run in a bucket of rows, the padding ones over zeros, so one graph serves any streams + const run = if (greedy) plan.bucketOf(rows, h.cap) else rows; + for (0..max_depth) |n| sc[h.cap + n] = @intCast(n); + for (0..run) |r| { + const real = r < jobs.len; + sc[r] = if (real) @intCast(jobs[r].token) else 0; + for (0..max_depth) |n| sc[at.pos / 4 + n * h.cap + r] = @intCast(n + if (real) jobs[r].position else 0); + srcs[at.ptrs / 8 + r] = if (real) jobs[r].hidden else h.zero.base(); + } + try hip.raw.upload(h.scalars_dev, 0, h.scalars.bytes[0..at.drafts], o.stream); + const dev = h.scalars_dev.base(); + if (greedy) { + try h.chain(stream, o, m, .{ .rows = @intCast(run), .most = @intCast(most), .cut = cut }, graphs); + } else { + try pops.gather(o, dev + at.ptrs, h.rows.base(), width / 4, rows); + var cur: Tensor = .{ .ptr = h.rows.base(), .kind = m.act }; + var reqs: [64]draw.Request = undefined; + var drawn: [64]u32 = undefined; + for (0..most) |n| { + const logits = try h.step(o, m, h.logits_head, cur, dev, rows, dev + at.slots + 4 * n, dev + at.pos + 4 * h.cap * n, n); + for (jobs, 0..) |j, r| reqs[r] = .{ .sampling = j.sampling, .position = j.position + n + 1 }; + try drawer.draw(o, stream, logits, reqs[0..rows], drawn[0..rows], false); + for (jobs, 0..) |j, r| if (n < j.out.len) { + j.out[n] = drawn[r]; + }; + if (n + 1 < most) { + for (0..rows) |r| sc[r] = @intCast(drawn[r]); + try hip.raw.upload(h.scalars_dev, 0, h.scalars.bytes[0 .. 4 * rows], o.stream); + if (cut) try o.tokenProb(logits, rows, h.logits_head.n, dev, dev + at.probs + 4 * h.cap * n); + } + cur = .{ .ptr = h.last, .kind = m.act }; + } + } + if (greedy or cut) { + try hip.raw.download(h.scalars_dev, at.drafts, h.scalars.bytes[at.drafts..at.total], o.stream); + try stream.synchronize(); + } + const words = h.scalars.slice(u32); + const chance = h.scalars.slice(f32); + for (jobs, 0..) |*j, r| { + const count = @min(j.depth, max_depth, j.out.len); + if (greedy) for (0..count) |n| { + j.out[n] = words[at.drafts / 4 + n * h.cap + r]; + }; + j.kept = count; + if (j.stop_under > 0.0) for (0..count -| 1) |n| if (chance[at.probs / 4 + n * h.cap + r] < j.stop_under) { + j.kept = n + 1; + break; + }; + } + } + + const Recording = struct { h: *Head, o: Ops, m: *const view.Model, key: ChainKey }; + + fn record(c: Recording) anyerror!void { + try c.h.launches(c.o, c.m, c.key); + } + + /// A greedy batch's launches: replayed from the shape's graph, captured the first time it is met, or eager. + fn chain(h: *Head, stream: hip.Stream, o: Ops, m: *const view.Model, key: ChainKey, graphs: bool) !void { + h.graphs.rounds += 1; + const entry = if (graphs) try h.graphs.find(key) else null; + if (entry) |e| switch (e.state) { + .ready => { + try e.exec.?.launchOn(stream); + h.graphs.replayed += 1; + return; + }, + .seen => { + if (try graph_cache.Cache(ChainKey, void).record(stream, Recording{ .h = h, .o = o, .m = m, .key = key }, record)) |rec| { + if (h.graphs.keep(e, rec.graph, stream, {})) { + try e.exec.?.launchOn(stream); + return; + } else |_| {} + } + e.state = .failed; + h.arena.reset(); + }, + .failed => {}, + }; + try h.launches(o, m, key); + } + + /// The chains' input rows gathered, then every step. + fn launches(h: *Head, o: Ops, m: *const view.Model, key: ChainKey) !void { + try pops.gather(o, h.scalars_dev.base() + h.layout().ptrs, h.rows.base(), m.spec.hidden * m.act.size() / 4, key.rows); + try h.steps(o, m, h.draft_head, key.rows, key.most, key.cut); + } + + /// The greedy chains' steps on the device alone: each step's drafts feed the next, with probabilities for the cut. + fn steps(h: *Head, o: Ops, m: *const view.Model, head: view.Projection, rows: usize, most: usize, cut: bool) !void { + const at = h.layout(); + const dev = h.scalars_dev.base(); + var cur: Tensor = .{ .ptr = h.rows.base(), .kind = m.act }; + for (0..most) |n| { + const drafts = dev + at.drafts + 4 * h.cap * n; + const ids = if (n == 0) dev else drafts - 4 * h.cap; + const logits = try h.step(o, m, head, cur, ids, rows, dev + at.slots + 4 * n, dev + at.pos + 4 * h.cap * n, n); + try o.argmaxRows(logits, rows, head.n, drafts); + if (cut and n + 1 < most) try o.tokenProb(logits, rows, head.n, 0, dev + at.probs + 4 * h.cap * n); + cur = .{ .ptr = h.last, .kind = m.act }; + } + } + + /// One head step over `rows` chains at their rope positions, writing each chain's slot; the logits rows come back. + fn step(h: *Head, o: Ops, m: *const view.Model, head: view.Projection, hidden: Tensor, ids: u64, rows: usize, slot_at: u64, pos: u64, slot: usize) !Tensor { + const s = m.spec; + const w = h.w; + const eps: f32 = @floatCast(s.eps); + const hd = s.head_dim; + const emb = try fwd.take(o, m.act, rows * s.hidden); + try o.embedRows(m.embed, ids, rows, emb); + const emb_e = try fwd.take(o, m.act, rows * s.hidden); + try o.rms(emb, w.fc_e_norm.ptr, emb_e, rows, s.hidden, eps); + const emb_h = try fwd.take(o, m.act, rows * s.hidden); + try o.rms(hidden, w.fc_h_norm.ptr, emb_h, rows, s.hidden, eps); + const e_proj = try project(o, w.fc_e, emb_e, rows); + const h_proj = try project(o, w.fc_h, emb_h, rows); + const x = try fwd.take(o, m.act, rows * s.hidden); + try o.add(e_proj, h_proj, x, rows * s.hidden); + var normed = x; + if (w.input_norm) |n| { + normed = try fwd.take(o, m.act, rows * s.hidden); + try o.rms(x, n.ptr, normed, rows, s.hidden, eps); + } + // the head's gated attention over each chain's cache (slots 0 .. slot), rope at the chain's position + const qg = try project(o, w.q, normed, rows); + const keys = try project(o, w.k, normed, rows); + const values = try project(o, w.v, normed, rows); + const qc = try fwd.take(o, m.act, rows * h.heads * hd); + try o.copyCols(qg, if (w.gated) 2 * hd else hd, 0, qc.ptr, rows * h.heads, hd); + const qn = try fwd.take(o, m.act, rows * h.heads * hd); + try o.rms(qc, w.q_norm.ptr, qn, rows * h.heads, hd, eps); + const kn = try fwd.take(o, m.act, rows * h.kv_heads * hd); + try o.rms(keys, w.k_norm.ptr, kn, rows * h.kv_heads, hd, eps); + const q32 = try ropeRows(o, m, qn, rows, h.heads, pos); + const k32 = try ropeRows(o, m, kn, rows, h.kv_heads, pos); + const kr = try fwd.take(o, m.act, rows * h.kv_heads * hd); + try o.cast(.{ .ptr = k32, .kind = .f32 }, kr, rows * h.kv_heads * hd); + const att = try o.arena.of(f32, rows * h.heads * hd); + for (0..rows) |r| { + const c: Ops.Cache = .{ .k = h.k.base() + r * h.cache_bytes, .v = h.v.base() + r * h.cache_bytes, .kind = m.act, .kv_heads = h.kv_heads, .total = max_depth + 1, .d = hd }; + try o.kvWrite(fwd.at(kr, r * h.kv_heads * hd), c.k, 1, h.kv_heads, hd, c.total, slot); + try o.kvWrite(fwd.at(values, r * h.kv_heads * hd), c.v, 1, h.kv_heads, hd, c.total, slot); + try o.causalAt(q32 + r * h.heads * hd * 4, c, att + r * h.heads * hd * 4, 1, h.heads, fwd.scaleOf(hd), slot_at); + } + const gated = try fwd.take(o, m.act, rows * h.heads * hd); + if (w.gated) { + try o.attnGate(att, qg, gated, rows, h.heads, hd, true); + } else try o.cast(.{ .ptr = att, .kind = .f32 }, gated, rows * h.heads * hd); + const attn_out = try project(o, w.o, gated, rows); + try o.add(x, attn_out, x, rows * s.hidden); + if (w.post_norm) |pn| if (h.mlp) |mlp| { + const xn = try fwd.take(o, m.act, rows * s.hidden); + try o.rms(x, pn.ptr, xn, rows, s.hidden, eps); + const y = try fwd.mlpRows(o, m, mlp, xn, rows, false); + try o.add(x, y, x, rows * s.hidden); + }; + const residual = try fwd.take(o, m.act, rows * s.hidden); + try o.rms(x, w.final_norm.ptr, residual, rows, s.hidden, eps); + h.last = residual.ptr; + return o.project(residual, head, rows, false); + } +}; + +/// The decode RoPE of `rows` rows of `heads` heads, each at its device position, in the activation dtype. +fn ropeRows(o: Ops, m: *const view.Model, x: Tensor, rows: usize, heads: usize, pos: u64) !u64 { + const s = m.spec; + const n = rows * heads * s.head_dim; + const wide = try o.arena.of(f32, n); + try o.cast(x, .{ .ptr = wide, .kind = .f32 }, n); + const turned = try o.arena.of(f32, n); + try o.ropeDecode(wide, turned, rows * heads, s.head_dim, s.rotary_dim, 0, @floatCast(s.rope_theta), pos, heads); + const narrow = try fwd.take(o, m.act, n); + try o.cast(.{ .ptr = turned, .kind = .f32 }, narrow, n); + const back = try o.arena.of(f32, n); + try o.cast(narrow, .{ .ptr = back, .kind = .f32 }, n); + return back; +} diff --git a/zig/src/families/qwen3_5/backend/hip/engine/native.zig b/zig/src/families/qwen3_5/backend/hip/engine/native.zig new file mode 100644 index 00000000000..9ef3064454b --- /dev/null +++ b/zig/src/families/qwen3_5/backend/hip/engine/native.zig @@ -0,0 +1,205 @@ +//! Qwen3.5 / Qwen3.6 for the native server on HIP: the engine sized to GPU memory and the lane backend over it. + +const std = @import("std"); +const hip = @import("hip"); +const lanes = @import("lanes"); +const engine = @import("engine.zig"); +const Engine = engine.Engine; +const memory = @import("memory.zig"); +const mtp = @import("mtp.zig"); +const prefix = @import("prefix.zig"); +const pages = @import("../forward/pages.zig"); +const state = @import("../forward/state.zig"); +const worker = @import("worker.zig"); +const hip_lanes = @import("hip_lanes.zig"); + +/// The MLX affine widths the family loads. +const mlx_formats: []const []const u8 = &.{ "mlx-q2", "mlx-q3", "mlx-q4", "mlx-q5", "mlx-q6", "mlx-q8" }; + +/// The dense and the sparse checkpoints are two registry entries over one engine. +pub fn Native(comptime type_name: []const u8) type { + return struct { + pub const model_type = type_name; + pub const formats = mlx_formats; + /// Positions a stream holds when neither --context nor the checkpoint's config names a window. + pub const default_context: i64 = 32768; + /// The engine cuts prompts itself. + pub const prefill_step: u32 = 0; + pub const open = openEngine; + pub const follow = followRank; + }; +} + +/// What the serve flags ask of the engine, as the host read them. +pub const Options = struct { + /// Prompt plus reply tokens a request may use: --context, or the family default within the model's window. + window: usize, + /// Streams asked for at once; `fixed` when --parallel named the number, which then fits or is refused. + streams: usize, + fixed: bool = false, + /// This process is `rank` of `world`. + rank: u32 = 0, + world: u32 = 1, + /// Bytes kept prompt states may hold (null: the policy's, else what the streams leave) and their snapshot slots. + cache_gib: ?f64 = null, + /// A --prompt-cache-gib past what the streams leave is kept, not refused. + cache_over_cap: bool = false, +}; + +/// What the native server drives: the lane backend, the facts its round loop reads, and how to free it. +pub const Loaded = struct { + backend: lanes.backend.Backend, + facts: lanes.Model, + rows: u32, + ctx: *anyopaque, + deinit: *const fn (*anyopaque) void, + /// The streams admitted at once, and the server's startup line (the memory plan). + streams: usize, + startup: []const u8, +}; + +/// A flag or a resource the engine cannot take: `problem` says why. +pub const Refused = error{Refused}; + +fn refuse(a: std.mem.Allocator, problem: *[]const u8, comptime fmt: []const u8, args: anytype) Refused { + problem.* = std.fmt.allocPrint(a, fmt, args) catch fmt; + return error.Refused; +} + +fn gibs(bytes: usize) f64 { + return @as(f64, @floatFromInt(bytes)) / (1 << 30); +} + +/// One rank's loaded and sized engine: the streams and prompt cache every rank agreed on. +const Prepared = struct { + e: *Engine, + streams: usize, + /// What the prompt cache holds: pages of the pool and linear snapshots (none when it is off). + cache: memory.Cache, + startup: []const u8, +}; + +/// Device bytes of `streams` lanes at `capacity` beside the weights; the prompt cache takes what is left. +fn served(e: *Engine, streams: usize, capacity: usize) !usize { + const rows = streams * hip_lanes.Hip.max_window; + return e.planBytes(streams, rows, capacity, streams * pages.pagesFor(capacity) + pages.pagesFor(rows), 0); +} + +/// Loads this rank's share of the model, admits the streams its memory holds (with the other ranks) and sizes them. +fn prepare(a: std.mem.Allocator, gpa: std.mem.Allocator, io: std.Io, dev: hip.Device, dir: []const u8, o: Options, problem: *[]const u8) (Refused || std.mem.Allocator.Error)!Prepared { + const rows = hip_lanes.Hip.max_window; + const held = hip.usage(false).device; + var pf: engine.Preflight = .{}; + const e = Engine.load(gpa, io, dir, .{ + .preflight = &pf, + .slack = rows + 1, + .device = dev.index, + .policy = dev.policy, + .rank = o.rank, + .world = o.world, + .group = dev.group, + }) catch |err| return switch (err) { + error.WeightsDoNotFit => refuse(a, problem, "the checkpoint's {d:.1} GiB of weights do not fit the {d:.1} GiB the HIP memory budget grants ({d:.1} GiB free less a {d:.1} GiB reserve{s}); free device memory or adjust TENSORFOLD_MEMORY_RESERVE_GIB / TENSORFOLD_HIP_MEMORY_LIMIT_GB", .{ gibs(pf.weights), gibs(pf.pool.room(pf.held)), gibs(pf.pool.free), gibs(pf.pool.reserve), if (pf.pool.limit != null) ", under TENSORFOLD_HIP_MEMORY_LIMIT_GB" else "" }), + error.BadReserve => refuse(a, problem, "TENSORFOLD_MEMORY_RESERVE_GIB: a number of GiB from 2 to the memory's size", .{}), + error.BadLimit => refuse(a, problem, "TENSORFOLD_HIP_MEMORY_LIMIT_GB: a positive number of GiB whose byte count fits in a 64-bit size", .{}), + error.HostMemoryUnavailable => refuse(a, problem, "cannot read or parse /proc/meminfo's MemTotal and MemAvailable; refusing HIP unified-memory admission", .{}), + else => refuse(a, problem, "the native HIP engine cannot load {s} ({s})", .{ dir, @errorName(err) }), + }; + errdefer e.deinit(); + const model = hip.usage(false).device - held; + const after = e.budget(io) catch |err| return refuse(a, problem, "the native HIP engine cannot read the GPU's memory ({s})", .{@errorName(err)}); + const room = after.room(model); + const reserve = after.reserve; + const capacity = o.window + rows + 1; + // the most streams up to the ones asked whose bytes fit, then the least of that over the ranks + var streams = o.streams; + while (streams > 0) : (streams -= 1) { + if ((served(e, streams, capacity) catch |err| return refuse(a, problem, "the native HIP engine cannot count its scratch ({s})", .{@errorName(err)})) <= room) break; + } + if (o.world > 1) streams = (e.least(.{ streams, 0 }) catch |err| return refuse(a, problem, "the ranks could not agree on the streams ({s})", .{@errorName(err)}))[0]; + if (streams == 0) { + const one = served(e, 1, capacity) catch 0; + return refuse(a, problem, "the HIP memory budget fits no stream: one at a {d}-token window takes {d:.2} GiB, and {d:.2} GiB is left after the model's {d:.2} GiB and the {d:.1} GiB reserve; lower --context, add ranks (--tp), or free device memory", .{ o.window, gibs(one), gibs(room), gibs(model), gibs(reserve) }); + } + if (streams < o.streams and o.fixed) { + const asked = served(e, o.streams, capacity) catch 0; + return refuse(a, problem, "--parallel {d} needs {d:.2} GiB at a {d}-token window, and the HIP memory budget leaves {d:.2} GiB: serve --parallel {d}, or lower --context", .{ o.streams, gibs(asked), o.window, gibs(room), streams }); + } + const need = served(e, streams, capacity) catch |err| return refuse(a, problem, "the native HIP engine cannot count its scratch ({s})", .{@errorName(err)}); + // the prompt cache: --prompt-cache-gib, else what the streams leave + const left = room - need; + const policy = dev.policy; + const keep: usize = policy.slots; + var budget: usize = if (o.cache_gib) |g| @intFromFloat(g * (1 << 30)) else left; + if (budget > left and !o.cache_over_cap) { + return refuse(a, problem, "a {d:.2} GiB prompt cache does not fit the {d:.2} GiB the streams leave; lower --prompt-cache-gib, or --prompt-cache-over-cap to keep it", .{ gibs(budget), gibs(left) }); + } + if (keep == 0) budget = 0; + var cache = memory.cache(e.weights.spec, e.act.size(), budget, keep); + if (o.world > 1) { + const fit = e.least(.{ cache.pages, cache.snaps }) catch |err| return refuse(a, problem, "the ranks could not agree on a prompt cache ({s})", .{@errorName(err)}); + cache = .{ .pages = fit[0], .snaps = fit[1] }; + } + e.o.batch_rows = streams * rows; + e.o.streams = streams; + e.size(capacity, streams * pages.pagesFor(capacity) + pages.pagesFor(e.o.batch_rows) + cache.pages) catch |err| + return refuse(a, problem, "the native HIP engine cannot allocate its scratch and pages ({s})", .{@errorName(err)}); + const lane = gibs(state.Caches.deviceBytes(e.model(), capacity) + pages.pagesFor(capacity) * memory.pageBytes(e.weights.spec, e.act.size())); + const startup = try std.fmt.allocPrint(gpa, "HIP {s} device {d}, rank {d} of {d}: model {d:.2} GiB; {d} stream{s} at once, {d:.2} GiB each at a {d}-token window, of {d:.1} GiB left after a {d:.1} GiB reserve; prompt cache {d:.2} GiB ({d} pages, {d} snapshots); prompts in {d}-row chunks", .{ + hip.kernels.arch, dev.index, o.rank, o.world, gibs(model), streams, if (streams == 1) "" else "s", lane, o.window, gibs(room), gibs(reserve), gibs(budget), cache.pages, cache.snaps, prefix.chunk, + }); + return .{ .e = e, .streams = streams, .cache = cache, .startup = startup }; +} + +const Owned = struct { + gpa: std.mem.Allocator, + e: *Engine, + backend: *hip_lanes.Hip, + startup: []const u8, +}; + +fn release(p: *anyopaque) void { + const own: *Owned = @ptrCast(@alignCast(p)); + // the other ranks hear that the rounds are over, then every rank frees its share + own.backend.deinit(); + own.e.deinit(); + own.gpa.free(own.startup); + own.gpa.destroy(own); +} + +/// The engine for `dir` on `dev`; under tensor parallelism this is rank 0, which serves. +fn openEngine(a: std.mem.Allocator, gpa: std.mem.Allocator, io: std.Io, dev: hip.Device, dir: []const u8, o: Options, problem: *[]const u8) anyerror!Loaded { + const p = try prepare(a, gpa, io, dev, dir, o, problem); + errdefer p.e.deinit(); + errdefer gpa.free(p.startup); + const own = try gpa.create(Owned); + errdefer gpa.destroy(own); + const before = hip.usage(false).device; + own.* = .{ .gpa = gpa, .e = p.e, .backend = try hip_lanes.Hip.init(gpa, p.e), .startup = p.startup }; + errdefer own.backend.deinit(); + // the head is the one allocation of the plan made here: it holds what the plan counted for it + const head = mtp.Head.deviceBytes(gpa, &p.e.driver, &p.e.lib, &p.e.weights, p.e.model(), @min(p.e.o.batch_rows, mtp.max_chains)) catch 0; + if (hip.usage(false).device - before != head) return refuse(a, problem, "the draft head holds {d} device bytes, the plan says {d}", .{ hip.usage(false).device - before, head }); + if (p.cache.pages > 0) own.backend.keepPages(p.cache.pages, p.cache.snaps); + // a lone rank times its forwards for the depth rule; the ranks of a group draft without costs + if (dev.group) |g| own.backend.withLink(g.link()) else own.backend.measure(); + return .{ + .backend = own.backend.backend(), + .facts = own.backend.facts(), + .rows = hip_lanes.Hip.max_window, + .ctx = own, + .deinit = release, + .streams = p.streams, + .startup = p.startup, + }; +} + +/// A rank above 0: holds its share of the model and runs rank 0's steps until rank 0 stops. +fn followRank(a: std.mem.Allocator, gpa: std.mem.Allocator, io: std.Io, dev: hip.Device, dir: []const u8, o: Options, problem: *[]const u8) anyerror!void { + const p = try prepare(a, gpa, io, dev, dir, o, problem); + defer p.e.deinit(); + defer gpa.free(p.startup); + var w = try worker.Worker.init(gpa, p.e); + defer w.deinit(); + try w.follow(dev.group.?.link()); +} diff --git a/zig/src/families/qwen3_5/backend/hip/engine/prefix.zig b/zig/src/families/qwen3_5/backend/hip/engine/prefix.zig new file mode 100644 index 00000000000..15ee1d22a3e --- /dev/null +++ b/zig/src/families/qwen3_5/backend/hip/engine/prefix.zig @@ -0,0 +1,26 @@ +//! The chunks a prompt pass runs in, and the gap between the snapshots it keeps. + +const std = @import("std"); +const pages = @import("../forward/pages.zig"); + +/// A snapshot this close to the prompt's end saves too little to keep next to the one before it. +pub const min_gap = 256; + +/// Cuts sit on page edges, multiples of the recurrence's chunk, so a resumed span chunks as a fresh prompt does. +pub const step = pages.tokens; + +/// Rows a prompt pass advances between two rounds when no other stream decodes; steps end on multiples of it. +pub const chunk = 1024; + +/// Where the step from `at` ends: the next multiple of `rows`, or `limit` when that comes first. +pub fn chunkEnd(at: usize, limit: usize, rows: usize) usize { + return @min(limit, (at / rows + 1) * rows); +} + +test "a prompt step ends on the next multiple of its rows, or the prompt's cut" { + try std.testing.expectEqual(@as(usize, 1024), chunkEnd(0, 5000, chunk)); + try std.testing.expectEqual(@as(usize, 512), chunkEnd(0, 5000, 512)); + try std.testing.expectEqual(@as(usize, 1024), chunkEnd(512, 5000, 512)); + try std.testing.expectEqual(@as(usize, 1024), chunkEnd(700, 5000, chunk)); + try std.testing.expectEqual(@as(usize, 900), chunkEnd(700, 900, 512)); +} diff --git a/zig/src/families/qwen3_5/backend/hip/engine/round.zig b/zig/src/families/qwen3_5/backend/hip/engine/round.zig new file mode 100644 index 00000000000..10be7123eef --- /dev/null +++ b/zig/src/families/qwen3_5/backend/hip/engine/round.zig @@ -0,0 +1,251 @@ +//! A lane round on the engine: its device plan, its forward (replayed, captured or eager), its draws and its keep. + +const std = @import("std"); +const hip = @import("hip"); +const state = @import("../forward/state.zig"); +const win = @import("../forward/window.zig"); +const fwd = @import("../forward/forward.zig"); +const plan = @import("../forward/plan.zig"); +const view = @import("../model/view.zig"); +const draw = @import("draw.zig"); +const round_graphs = @import("round_graphs.zig"); +const Engine = @import("engine.zig").Engine; + +/// What a round does with its shape's graph: run eagerly, replay it, or capture it (every rank does the same). +pub const Pick = enum(u32) { eager, replay, capture }; + +/// What a verify hands back: the round's final rows, padding included. +pub const Verified = struct { hidden: hip.ops.Tensor }; + +/// One stream's rows of a round: tokens (the pending one, then drafts) from slot `pos` over its caches. +pub const Rows = struct { caches: *state.Caches, pos: usize, tokens: []const u32 }; + +const Chosen = struct { pick: Pick, entry: ?*round_graphs.Entry, shape: plan.Shape }; + +/// The slots a keep names and the plan they index. +const Last = struct { plan: hip.plan_ops.Plan, keep_at: usize, hidden: u64 }; + +/// Keep lists in flight: a flush's pinned words stay until its copy has run, which a later round's sync guarantees. +const keep_ring = 4; + +pub const State = struct { + buffer: plan.Buffer, + /// The caches the padding rows run in. + scratch: state.Caches, + /// Each linear layer's snapshots of the round in flight. + snaps: [][2]u64, + wins: []plan.Window, + /// The rows each slot keeps at the next flush (negative: not listed), and the pinned words they go up in. + staging: []i32, + keeps: hip.HostBuffer, + ring: usize = 0, + /// For checks: a layer-by-layer trace of the forward (graphs off), and a least bucket of rows. + trace: ?fwd.Trace = null, + pad_to: usize = 0, + chosen: ?Chosen = null, + last: ?Last = null, + /// The layout of the plan in flight, for the copy a round starts with. + layout: plan.Layout = undefined, + + pub fn init(e: *Engine) !State { + const m = e.model(); + if (!win.supported(e.ops(&e.rounds), m)) return error.RoundsUnsupported; + const rows = e.o.batch_rows; + var buffer = try plan.Buffer.init(&e.driver, rows, m.spec.n_layers, e.pool.count); + errdefer buffer.deinit(); + var scratch = try state.Caches.initFull(e.gpa, &e.pool, m, rows); + errdefer scratch.deinit(e.gpa); + const snaps = try e.gpa.alloc([2]u64, m.spec.n_layers); + errdefer e.gpa.free(snaps); + const wins = try e.gpa.alloc(plan.Window, rows); + errdefer e.gpa.free(wins); + const staging = try e.gpa.alloc(i32, rows + 1); + errdefer e.gpa.free(staging); + @memset(staging, -1); + return .{ .buffer = buffer, .scratch = scratch, .snaps = snaps, .wins = wins, .staging = staging, .keeps = try hip.HostBuffer.alloc(&e.driver, keep_ring * 4 * (rows + 1)) }; + } + + pub fn deinit(s: *State, e: *Engine) void { + s.keeps.free(); + e.gpa.free(s.staging); + e.gpa.free(s.wins); + e.gpa.free(s.snaps); + s.scratch.deinit(e.gpa); + s.buffer.deinit(); + } +}; + +/// The shape of a round of `rows`: its bucket of rows, its slots and the keys its walk covers. +pub fn shapeOf(e: *Engine, rows: []const Rows) !plan.Shape { + var total: usize = 0; + var visible: usize = 0; + for (rows) |r| { + total += r.tokens.len; + visible = @max(visible, r.pos + r.tokens.len); + } + if (rows.len == 0 or total == 0 or total > e.o.batch_rows) return error.WindowTooWide; + const cap = std.mem.alignForward(usize, e.o.capacity, plan.min_span); + const bucket = plan.bucketOf(@max(total, e.round.pad_to), e.o.batch_rows); + const slots = plan.bucketOf(rows.len + 1, e.o.batch_rows + 1); + return .{ .rows = @intCast(bucket), .slots = @intCast(slots), .span = @intCast(@min(plan.spanOf(visible), cap)) }; +} + +/// The round's graph choice: from the shape's history, or `forced` (rank 0's pick, which a follower obeys). +pub fn choose(e: *Engine, rows: []const Rows, forced: ?Pick) !Pick { + const st = &e.round; + const shape = try shapeOf(e, rows); + st.chosen = .{ .pick = .eager, .entry = null, .shape = shape }; + if (!e.o.graphs) { + if ((forced orelse .eager) != .eager) return error.GraphsDisagree; + return .eager; + } + const entry = try e.graphs.find(shape); + const mine: Pick = switch (entry.state) { + .failed => .eager, + .ready => .replay, + .seen => .capture, + }; + const pick = forced orelse mine; + if (pick == .replay and entry.state != .ready) return error.GraphsDisagree; + st.chosen = .{ .pick = pick, .entry = entry, .shape = shape }; + return pick; +} + +fn nowNs() u64 { + var ts: std.c.timespec = undefined; + _ = std.c.clock_gettime(.MONOTONIC, &ts); + return @as(u64, @intCast(ts.sec)) * 1_000_000_000 + @as(u64, @intCast(ts.nsec)); +} + +/// Every window in one forward: `out` the token of every row per `reqs`; snapshots live until the next round's `keep`. +pub fn verify(e: *Engine, rows: []const Rows, reqs: []const draw.Request, out: []u32) !Verified { + const st = &e.round; + const m = e.model(); + const began = nowNs(); + if (st.chosen == null) _ = try choose(e, rows, null); + const c = st.chosen.?; + defer st.chosen = null; + var total: usize = 0; + for (rows, 0..) |r, i| { + if (r.pos + r.tokens.len > r.caches.covered()) return error.ContextFull; + st.wins[i] = .{ .desc = r.caches.desc.base(), .pos = r.pos, .tokens = r.tokens }; + total += r.tokens.len; + } + e.rounds.reset(); + const o = e.ops(&e.rounds); + try win.kept(o, m, c.shape.rows, st.snaps); + const l = plan.Layout.of(c.shape.rows, c.shape.slots, m.spec.n_layers); + st.buffer.fill(l, c.shape, st.wins[0..rows.len], st.scratch.desc.base(), st.snaps); + st.layout = l; + const p: hip.plan_ops.Plan = .{ .args = st.buffer.args(l), .rows = c.shape.rows, .slots = c.shape.slots }; + const r: win.Round = .{ .plan = p, .tokens = st.buffer.dev.base() + 4 * l.tokens, .span = c.shape.span, .inputs = st.snaps }; + const done = try run(e, c, r); + e.graphs.rounds += 1; + e.graphs.submit_ns += nowNs() - began; + try e.drawRows(o, done.y, total, reqs, out, m.tp == null); + st.last = .{ .plan = p, .keep_at = 4 * l.keep, .hidden = done.hidden.ptr }; + return .{ .hidden = done.hidden }; +} + +/// The forward and its logits projection, and the greedy draw of every row when this rank holds the whole head. +fn body(e: *Engine, r: win.Round) !round_graphs.Out { + // the plan goes up first, inside the graph + try e.round.buffer.send(e.stream.handle, e.round.layout); + return forwardOn(e.ops(&e.rounds), e.model(), r, e.round.trace, e.drawer.argmaxAt()); +} + +/// `body` after the plan's copy, on `o`: on the counting stream it measures what a round takes. +pub fn forwardOn(ops: hip.ops.Ops, m: *const view.Model, r: win.Round, trace: ?fwd.Trace, argmax_at: u64) !round_graphs.Out { + var o = ops; + // a round's rows keep their decode kernels however many share it + o.window = true; + const hidden = try win.forward(o, m, r, trace); + const y = try o.project(hidden, m.head, r.plan.rows, false); + if (m.tp == null) try o.argmaxRows(y, r.plan.rows, m.head.n, argmax_at); + return .{ .hidden = hidden, .y = y, .used = o.arena.used }; +} + +/// One round's forward as `choose` picked: replayed from the shape's graph, captured, or eager. +fn run(e: *Engine, c: Chosen, r: win.Round) !round_graphs.Out { + const entry = c.entry orelse return body(e, r); + switch (c.pick) { + .eager => return body(e, r), + .replay => { + e.rounds.used = entry.out.used; + try entry.exec.?.launchOn(e.stream); + e.graphs.replayed += 1; + return entry.out; + }, + .capture => return capture(e, entry, r), + } +} + +const Recording = struct { e: *Engine, r: win.Round }; + +fn record(ctx: Recording) anyerror!round_graphs.Out { + return body(ctx.e, ctx.r); +} + +/// Records the round into a graph and launches it; a capture that fails on any rank runs eagerly on every rank. +fn capture(e: *Engine, entry: *round_graphs.Entry, r: win.Round) !round_graphs.Out { + var kept = false; + var out: round_graphs.Out = undefined; + const at = e.rounds.mark(); + const began = nowNs(); + if (try round_graphs.Graphs.record(e.stream, Recording{ .e = e, .r = r }, record)) |rec| { + out = rec.out; + kept = if (e.graphs.keep(entry, rec.graph, e.stream, rec.out)) true else |_| false; + } + // the policy's `graph_fail` makes that rank's capture fail, to check that every rank falls back + if (e.o.policy.graph_fail >= 0 and @as(usize, @intCast(e.o.policy.graph_fail)) == e.o.rank) kept = false; + e.graphs.capture_ns += nowNs() - began; + const all = if (e.o.world > 1) try agreed(e, kept) else kept; + if (!all) { + e.graphs.revoke(entry); + e.rounds.release(at); + return body(e, r); + } + try entry.exec.?.launchOn(e.stream); + return out; +} + +/// Whether every rank says yes (an all-gather of one word each). +fn agreed(e: *Engine, yes: bool) !bool { + const world = e.o.world; + var host = try hip.HostBuffer.alloc(&e.driver, 8 * (1 + world)); + defer host.free(); + var send = try hip.DeviceBuffer.alloc(&e.driver, 8); + defer send.free(); + var recv = try hip.DeviceBuffer.alloc(&e.driver, 8 * world); + defer recv.free(); + host.slice(u64)[0] = @intFromBool(yes); + try hip.raw.upload(send, 0, host.bytes[0..8], e.stream.handle); + try e.comm.allGather(send.base(), recv.base(), 1, .i64, e.stream.handle); + try hip.raw.download(recv, 0, host.bytes[8 .. 8 * (1 + world)], e.stream.handle); + try e.stream.synchronize(); + for (host.slice(u64)[1 .. 1 + world]) |v| if (v == 0) return false; + return true; +} + +/// Marks slot `slot` of the last verify to keep its first `rows` rows at the next `flush`. +pub fn mark(e: *Engine, slot: usize, rows: usize) void { + e.round.staging[slot] = @intCast(rows); +} + +/// Keeps every marked slot of the last verify in one launch: linear states after the kept rows, last kept final rows. +pub fn flush(e: *Engine) !void { + const st = &e.round; + const last = st.last orelse return; + const slots = last.plan.slots; + var any = false; + for (st.staging[0..slots]) |k| any = any or k >= 0; + if (!any) return; + const per = e.o.batch_rows + 1; + const from = 4 * st.ring * per; + const words = st.keeps.slice(i32)[st.ring * per ..][0..slots]; + st.ring = (st.ring + 1) % keep_ring; + @memcpy(words, st.staging[0..slots]); + @memset(st.staging[0..slots], -1); + try st.buffer.dev.uploadAsync(last.keep_at, st.keeps.view(from, from + 4 * slots), e.stream); + try win.keep(e.ops(&e.rounds), e.model(), last.plan, st.buffer.dev.base() + last.keep_at, last.hidden); +} diff --git a/zig/src/families/qwen3_5/backend/hip/engine/round_graphs.zig b/zig/src/families/qwen3_5/backend/hip/engine/round_graphs.zig new file mode 100644 index 00000000000..4228302d0bf --- /dev/null +++ b/zig/src/families/qwen3_5/backend/hip/engine/round_graphs.zig @@ -0,0 +1,12 @@ +//! Captured lane rounds: a round's forward recorded once per plan shape and replayed on any later round of it. + +const hip = @import("hip"); +const plan = @import("../forward/plan.zig"); +const graph_cache = @import("graph_cache.zig"); + +/// What a replay hands back: the forward's outputs and where the arena stands after it. +pub const Out = struct { hidden: hip.ops.Tensor, y: hip.ops.Tensor, used: usize }; + +pub const Graphs = graph_cache.Cache(plan.Shape, Out); + +pub const Entry = Graphs.Entry; diff --git a/zig/src/families/qwen3_5/backend/hip/engine/sample.zig b/zig/src/families/qwen3_5/backend/hip/engine/sample.zig new file mode 100644 index 00000000000..d0939841de2 --- /dev/null +++ b/zig/src/families/qwen3_5/backend/hip/engine/sample.zig @@ -0,0 +1,124 @@ +//! A row's token from its logits: argmax for greedy, else the keyed draw over top_k + MARGIN candidates. + +const std = @import("std"); +const lanes = @import("lanes"); +const Allocator = std.mem.Allocator; + +/// exact_sampling.MARGIN: candidates past top_k, so ties resolve by id on the host. +pub const MARGIN = 8; + +pub const Dtype = enum { f16, bf16 }; + +pub fn widen(row: []const u16, dtype: Dtype, i: usize) f32 { + return switch (dtype) { + .f16 => @floatCast(@as(f16, @bitCast(row[i]))), + .bf16 => @bitCast(@as(u32, row[i]) << 16), + }; +} + +/// torch.argmax over the widened row: the first index of the largest value (a NaN wins, as torch's). +pub fn argmax(row: []const u16, dtype: Dtype) u32 { + var best: usize = 0; + var top = widen(row, dtype, 0); + for (1..row.len) |i| { + const v = widen(row, dtype, i); + if (std.math.isNan(top)) break; + if (std.math.isNan(v) or v > top) { + best = i; + top = v; + } + } + return @intCast(best); +} + +/// Structured output: every token whose bit is clear in `bits` (32 a word, token i in word i / 32) becomes -inf. +pub fn mask(row: []u16, dtype: Dtype, bits: []const u32) void { + const minus_inf: u16 = switch (dtype) { + .f16 => 0xFC00, + .bf16 => 0xFF80, + }; + for (row, 0..) |*v, i| { + const word = i / 32; + const allowed = word < bits.len and (bits[word] >> @intCast(i % 32)) & 1 == 1; + if (!allowed) v.* = minus_inf; + } +} + +const Candidate = struct { value: f32, id: u32 }; + +fn larger(_: void, a: Candidate, b: Candidate) bool { + return a.value > b.value or (a.value == b.value and a.id < b.id); +} + +/// draw(): greedy (no sampling or temperature <= 0) is the argmax; else `choose` at `position` over the candidates. +pub fn draw(gpa: Allocator, row: []const u16, dtype: Dtype, sampling: ?lanes.Sampling, position: u64) !u32 { + const s = sampling orelse return argmax(row, dtype); + if (s.temperature <= 0.0) return argmax(row, dtype); + const width = row.len; + const count = if (s.top_k != 0) @min(width, @as(usize, s.top_k) + MARGIN) else width; + const best = try gpa.alloc(Candidate, count); + defer gpa.free(best); + var filled: usize = 0; + // the whole row when top_k is 0 (choose orders it), else the top `count` by value then id in one pass + if (count == width) { + for (best, 0..) |*c, i| c.* = .{ .value = widen(row, dtype, i), .id = @intCast(i) }; + filled = width; + } else for (0..width) |i| { + const c: Candidate = .{ .value = widen(row, dtype, i), .id = @intCast(i) }; + if (filled == count and !larger({}, c, best[count - 1])) continue; + var at = if (filled < count) filled else count - 1; + if (filled < count) filled += 1; + while (at > 0 and larger({}, c, best[at - 1])) : (at -= 1) best[at] = best[at - 1]; + best[at] = c; + } + const values = try gpa.alloc(f64, count); + defer gpa.free(values); + const ids = try gpa.alloc(u64, count); + defer gpa.free(ids); + for (best, values, ids) |c, *v, *id| { + v.* = c.value; + id.* = c.id; + } + return @intCast(try lanes.sampling.choose(gpa, values, ids, position, s)); +} + +/// The softmax probability of `id` in the widened row (the MTP chain's confidence cut), in double. +pub fn probability(row: []const u16, dtype: Dtype, id: u32) f64 { + var top: f64 = -std.math.inf(f64); + for (0..row.len) |i| top = @max(top, widen(row, dtype, i)); + var total: f64 = 0; + for (0..row.len) |i| total += @exp(@as(f64, widen(row, dtype, i)) - top); + return @exp(@as(f64, widen(row, dtype, id)) - top) / total; +} + +test "argmax keeps the first of equal values; bf16 and fp16 widen exactly" { + const one_bf16: u16 = 0x3f80; + const row = [_]u16{ 0, one_bf16, one_bf16, 0 }; + try std.testing.expectEqual(@as(u32, 1), argmax(&row, .bf16)); + const one_f16: u16 = 0x3c00; + try std.testing.expectEqual(@as(f32, 1.0), widen(&.{one_f16}, .f16, 0)); +} + +test "greedy draws the argmax" { + const row = [_]u16{ 0x3c00, 0x4000, 0x3e00 }; + try std.testing.expectEqual(@as(u32, 1), try draw(std.testing.allocator, &row, .f16, null, 0)); +} + +test "a masked row draws only allowed tokens, greedy and sampled" { + const bf: u16 = 0x3f80; // 1.0 + const big: u16 = 0x4000; // 2.0 + var row = [_]u16{ big, bf, 0, bf, big }; + // tokens 1 and 3 allowed: the largest allowed is 1 (first of equals), not 0 or 4 + mask(&row, .bf16, &.{0b01010}); + try std.testing.expectEqual(@as(u32, 1), argmax(&row, .bf16)); + try std.testing.expectEqual(@as(u16, 0xFF80), row[0]); + const s: lanes.Sampling = .{ .seed = 3, .temperature = 1.0 }; + for (0..32) |p| { + const t = try draw(std.testing.allocator, &row, .bf16, s, p); + try std.testing.expect(t == 1 or t == 3); + } + // a mask shorter than the row disallows the rest + var tail = [_]u16{ bf, bf, big }; + mask(&tail, .f16, &.{}); + try std.testing.expectEqual(@as(u16, 0xFC00), tail[2]); +} diff --git a/zig/src/families/qwen3_5/backend/hip/engine/scratch.zig b/zig/src/families/qwen3_5/backend/hip/engine/scratch.zig new file mode 100644 index 00000000000..83117340c65 --- /dev/null +++ b/zig/src/families/qwen3_5/backend/hip/engine/scratch.zig @@ -0,0 +1,48 @@ +//! The scratch each arena needs: the forwards themselves run on the counting stream at their largest shapes. + +const std = @import("std"); +const hip = @import("hip"); +const fwd = @import("../forward/forward.zig"); +const win = @import("../forward/window.zig"); +const pages = @import("../forward/pages.zig"); +const state = @import("../forward/state.zig"); +const plan = @import("../forward/plan.zig"); +const round = @import("round.zig"); +const Engine = @import("engine.zig").Engine; + +/// A prompt pass of `rows` rows ending at the last of `capacity` positions, then the head over its last row. +pub fn prompts(e: *Engine, rows: usize, capacity: usize) !usize { + const m = e.model(); + var pool = try pages.Pool.init(e.gpa, &e.driver, m, 1, false); + defer pool.deinit(); + var caches = try state.Caches.init(e.gpa, &pool, m, capacity); + defer caches.deinit(e.gpa); + var arena = hip.Arena.counting(); + const o = counting(e, &arena); + // every take grows with the rows and the keys walked, so the last chunk of a full window is the largest + const hidden = try fwd.span(o, m, &caches, 0, rows, capacity - rows, null); + const y = try o.project(fwd.at(hidden, (rows - 1) * m.spec.hidden), m.head, 1, false); + _ = try e.wholeRows(o, y, 1); + return arena.peak; +} + +/// A round of `rows` rows whose attention walks every position of `capacity`: snapshots, forward, whole logits. +pub fn rounds(e: *Engine, rows: usize, capacity: usize) !usize { + const m = e.model(); + const table = try e.gpa.alloc([2]u64, m.spec.n_layers); + defer e.gpa.free(table); + var arena = hip.Arena.counting(); + const o = counting(e, &arena); + try win.kept(o, m, rows, table); + const p: hip.plan_ops.Plan = .{ .args = std.mem.zeroes(@FieldType(hip.plan_ops.Plan, "args")), .rows = rows, .slots = rows + 1 }; + const r: win.Round = .{ .plan = p, .tokens = 0, .span = std.mem.alignForward(usize, capacity, plan.min_span), .inputs = table }; + const out = try round.forwardOn(o, m, r, null, 0); + _ = try e.wholeRows(o, out.y, rows); + return arena.peak; +} + +fn counting(e: *Engine, arena: *hip.Arena) hip.ops.Ops { + var o = e.ops(arena); + o.stream = hip.counting; + return o; +} diff --git a/zig/src/families/qwen3_5/backend/hip/engine/worker.zig b/zig/src/families/qwen3_5/backend/hip/engine/worker.zig new file mode 100644 index 00000000000..b390ca80442 --- /dev/null +++ b/zig/src/families/qwen3_5/backend/hip/engine/worker.zig @@ -0,0 +1,169 @@ +//! A tensor-parallel rank above 0: runs the steps rank 0 sends in the same order, so the collectives pair up. + +const std = @import("std"); +const hip = @import("hip"); +const Engine = @import("engine.zig").Engine; +const Pick = @import("engine.zig").Pick; +const state = @import("../forward/state.zig"); +const draw = @import("draw.zig"); + +/// A message's first word: rank 0 decides every match, eviction, page and slot, and a rank only applies it. +pub const Op = enum(u32) { stop, prefill, verify, keep, release, fill, pages, snap, copy }; + +/// The prefill message's snapshot slot when the pass starts from nothing. +pub const no_snapshot: u32 = std.math.maxInt(u32); + +/// Windows a round holds at most. +const max_windows = 128; + +const Fill = struct { prompt: []u32, at: usize }; + +const Lane = struct { + caches: state.Caches, + /// Slots written and kept: the next window starts here. + len: usize, + /// The prompt pass in progress: the prompt and the row it has reached. + fill: ?Fill = null, + /// The last verify's slot and rows, until rank 0's keep. + pending: ?struct { window: usize, rows: usize } = null, +}; + +pub const Worker = struct { + gpa: std.mem.Allocator, + e: *Engine, + lanes: std.AutoHashMapUnmanaged(u32, *Lane) = .empty, + reqs: []draw.Request, + out: []u32, + /// The linear snapshots of rank 0's prefix tree, in the slots it names. + snaps: state.Snapshots, + + pub fn init(gpa: std.mem.Allocator, e: *Engine) !Worker { + const rows = e.o.batch_rows; + const reqs = try gpa.alloc(draw.Request, rows); + errdefer gpa.free(reqs); + // a follower's draws are greedy and unread: the forward and its collectives are what it shares + @memset(reqs, .{ .sampling = null, .position = 0 }); + return .{ .gpa = gpa, .e = e, .reqs = reqs, .out = try gpa.alloc(u32, rows), .snaps = state.Snapshots.init(gpa, &e.driver) }; + } + + pub fn deinit(w: *Worker) void { + w.e.stream.synchronize() catch {}; + w.snaps.deinit(); + var it = w.lanes.valueIterator(); + while (it.next()) |l| w.destroy(l.*); + w.lanes.deinit(w.gpa); + w.gpa.free(w.out); + w.gpa.free(w.reqs); + } + + fn destroy(w: *Worker, l: *Lane) void { + if (l.fill) |f| w.gpa.free(f.prompt); + w.e.drain(); + l.caches.deinit(w.gpa); + w.gpa.destroy(l); + } + + fn prefill(w: *Worker, id: u32, total: usize, prompt: []const u32, at: usize, snap: ?u32, held: []const u32) !void { + const gop = try w.lanes.getOrPut(w.gpa, id); + if (gop.found_existing) w.destroy(gop.value_ptr.*); + errdefer w.lanes.removeByPtr(gop.key_ptr); + const lane = try w.gpa.create(Lane); + errdefer w.gpa.destroy(lane); + lane.* = .{ .caches = try w.e.emptyCaches(total), .len = prompt.len }; + errdefer lane.caches.deinit(w.gpa); + try lane.caches.set(w.gpa, 0, held); + if (snap) |slot| try w.snaps.put(slot, &lane.caches, w.e.stream.handle); + lane.fill = .{ .prompt = try w.gpa.dupe(u32, prompt), .at = at }; + gop.value_ptr.* = lane; + } + + /// The next chunk of a prompt pass, to row `to`: rank 0's cuts and chunk ends, run the same way. + fn fill(w: *Worker, id: u32, to: usize) !void { + const lane = w.lanes.get(id) orelse return error.UnknownStream; + const f = &(lane.fill orelse return error.NoPromptPass); + if (to == f.prompt.len) { + _ = try w.e.prefill(&lane.caches, f.prompt, f.at, null, w.reqs[0], null); + w.gpa.free(f.prompt); + lane.fill = null; + return; + } + try w.e.advance(&lane.caches, f.prompt, f.at, to, null); + f.at = to; + } + + fn laneOf(w: *Worker, id: u32) !*Lane { + return w.lanes.get(id) orelse error.UnknownStream; + } + + fn verify(w: *Worker, ids: []const u32, rows: []const Engine.Rows, pick: Pick) !void { + var total: usize = 0; + for (rows) |r| total += r.tokens.len; + _ = try w.e.choose(rows, pick); + _ = try w.e.verify(rows, w.reqs[0..total], w.out[0..total]); + for (ids, 0..) |id, i| w.lanes.get(id).?.pending = .{ .window = i, .rows = rows[i].tokens.len }; + } + + fn keep(w: *Worker, id: u32, rows: usize) !void { + const lane = w.lanes.get(id) orelse return error.UnknownStream; + const p = lane.pending orelse return error.NothingToKeep; + w.e.keep(p.window, rows); + lane.len += rows; + lane.pending = null; + } + + fn release(w: *Worker, id: u32) void { + const kv = w.lanes.fetchRemove(id) orelse return; + w.e.stream.synchronize() catch {}; + w.destroy(kv.value); + } + + /// Runs rank 0's steps until it says stop. + pub fn follow(w: *Worker, link: hip.collective.Link) !void { + var msg: std.ArrayList(u32) = .empty; + defer msg.deinit(w.gpa); + var ids: [max_windows]u32 = undefined; + var rows: [max_windows]Engine.Rows = undefined; + while (true) { + try link.recv(w.gpa, &msg); + const m = msg.items; + switch (@as(Op, @fromBackingInt(@as(u32, @intCast(m[0]))))) { + .stop => return, + // prefill: id, positions, prompt len, resumed at, cut count, snapshot slot, page count, then the pages + .prefill => { + const held = m[8..][0..m[7]]; + // the cuts sit between the pages and the prompt + const prompt = m[8 + m[7] + m[5] ..][0..m[3]]; + try w.prefill(m[1], m[2], prompt, m[4], if (m[6] == no_snapshot) null else m[6], held); + }, + // verify: graph pick, count, then id, rows, tokens each; every rank derives the plan shape from them + .verify => { + const pick: Pick = @fromBackingInt(m[1]); + const n = m[2]; + if (n > max_windows) return error.WindowTooWide; + var at: usize = 3; + for (0..n) |i| { + const lane = w.lanes.get(m[at]) orelse return error.UnknownStream; + ids[i] = m[at]; + rows[i] = .{ .caches = &lane.caches, .pos = lane.len, .tokens = m[at + 2 ..][0..m[at + 1]] }; + at += 2 + m[at + 1]; + } + try w.verify(ids[0..n], rows[0..n], pick); + }, + // keep: count, then id and rows each + .keep => { + for (0..m[1]) |i| try w.keep(m[2 + 2 * i], m[3 + 2 * i]); + try w.e.flush(); + }, + .release => w.release(m[1]), + // fill: id, end of the prompt pass's next chunk + .fill => try w.fill(m[1], m[2]), + // pages: id, first page index, count, then the stream's table from that index on + .pages => try (try w.laneOf(m[1])).caches.set(w.gpa, m[2], m[4..][0..m[3]]), + // snap: id, slot that keeps the stream's linear state + .snap => try w.snaps.take(m[2], &(try w.laneOf(m[1])).caches, w.e.stream.handle), + // copy: from, to; page `to` becomes a copy of page `from` + .copy => try w.e.pool.copyPage(m[1], m[2], w.e.stream.handle), + } + } + } +}; diff --git a/zig/src/families/qwen3_5/backend/hip/forward/forward.zig b/zig/src/families/qwen3_5/backend/hip/forward/forward.zig new file mode 100644 index 00000000000..6205c2b7525 --- /dev/null +++ b/zig/src/families/qwen3_5/backend/hip/forward/forward.zig @@ -0,0 +1,187 @@ +//! A prompt span through every layer in steps of SPAN rows, on the prefill formulas. + +const std = @import("std"); +const hip = @import("hip"); +const view = @import("../model/view.zig"); +const state = @import("state.zig"); +const moe = @import("moe.zig"); +const reduce = @import("reduce.zig"); + +const Ops = hip.ops.Ops; +const Tensor = hip.ops.Tensor; +const Kind = hip.ops.Kind; + +/// Rows of one prefill step (qwen_math.SPAN). +pub const SPAN = 2048; + +pub const Error = reduce.Error || error{Cancelled}; + +pub const residual = reduce.residual; + +/// A device buffer of `n` values of `kind` from the arena. +pub fn take(o: Ops, kind: Kind, n: usize) Error!Tensor { + return .{ .ptr = try o.arena.take(n * kind.size()), .kind = kind }; +} + +/// `t` advanced by `n` values. +pub fn at(t: Tensor, n: usize) Tensor { + return .{ .ptr = t.ptr + n * t.kind.size(), .kind = t.kind }; +} + +/// Called after each layer with the residual rows (a check reads them; the forward does not wait for it). +pub const Trace = struct { + ctx: *anyopaque, + layer: *const fn (ctx: *anyopaque, index: usize, x: Tensor, rows: usize) anyerror!void, +}; + +/// The span's final-normed rows (len, hidden) in the activation dtype; `ids` are int32 token ids on the device. +pub fn span(ops: Ops, m: *const view.Model, caches: *state.Caches, ids: u64, len: usize, pos0: usize, trace: ?Trace) Error!Tensor { + // prefill's kernels at any row count: a prompt's rows have the same bits fresh, resumed or in steps + var o = ops; + o.prefill = true; + const s = m.spec; + const x = try take(o, m.act, len * s.hidden); + var start: usize = 0; + while (start < len) : (start += SPAN) { + const rows = @min(SPAN, len - start); + try o.embedRows(m.embed, ids + start * 4, rows, at(x, start * s.hidden)); + } + for (m.layers, 0..) |layer, index| { + start = 0; + while (start < len) : (start += SPAN) { + const rows = @min(SPAN, len - start); + const mark = o.arena.mark(); + defer o.arena.release(mark); + const xs = at(x, start * s.hidden); + const input_norm, const post_norm, const mlp = switch (layer) { + .full => |f| .{ f.input_norm, f.post_norm, f.mlp }, + .linear => |l| .{ l.input_norm, l.post_norm, l.mlp }, + }; + const normed = try take(o, m.act, rows * s.hidden); + try o.rms(xs, input_norm, normed, rows, s.hidden, @floatCast(s.eps)); + const y = switch (layer) { + .full => |f| try attention(o, m, f, caches, index, normed, rows, pos0 + start), + .linear => |l| try linear(o, m, l, caches, index, normed, rows), + }; + try residual(o, m, xs, y, rows * s.hidden); + try o.rms(xs, post_norm, normed, rows, s.hidden, @floatCast(s.eps)); + const z = try mlpRows(o, m, mlp, normed, rows, true); + try residual(o, m, xs, z, rows * s.hidden); + } + if (trace) |t| t.layer(t.ctx, index, x, len) catch |err| return if (err == error.Cancelled) error.Cancelled else error.HipFailed; + } + const out = try take(o, m.act, len * s.hidden); + try o.rms(x, m.final_norm, out, len, s.hidden, @floatCast(s.eps)); + return out; +} + +/// The attention scale, head_dim ** -0.5 in double as Python has it, passed as fp32. +pub fn scaleOf(head_dim: usize) f32 { + return @floatCast(std.math.pow(f64, @floatFromInt(head_dim), -0.5)); +} + +/// Full attention on `rows` normed rows at `pos`: q and its gate, k, v, norms, RoPE, cache write, prefill tile, o. +fn attention(o: Ops, m: *const view.Model, f: view.Full, caches: *state.Caches, index: usize, x: Tensor, rows: usize, pos: usize) Error!Tensor { + const s = m.spec; + const hd = s.head_dim; + const qg = try o.project(x, f.q, rows, false); + const keys = try o.project(x, f.k, rows, false); + const values = try o.project(x, f.v, rows, false); + const q_rows = rows * s.heads; + const qc = try take(o, m.act, q_rows * hd); + try o.copyCols(qg, 2 * hd, 0, qc.ptr, q_rows, hd); + const qn = try take(o, m.act, q_rows * hd); + try o.rms(qc, f.q_norm, qn, q_rows, hd, @floatCast(s.eps)); + const kn = try take(o, m.act, rows * s.kv_heads * hd); + try o.rms(keys, f.k_norm, kn, rows * s.kv_heads, hd, @floatCast(s.eps)); + const theta: f32 = @floatCast(s.rope_theta); + const q32 = try o.arena.of(f32, q_rows * hd); + // q rounded to the activation dtype by apply_rope, then widened for the kernel: (heads, rows, d) fp32 + try o.ropePrefill(qn, .{ .ptr = q32, .kind = .f32 }, rows * hd, hd, rows, s.heads, hd, s.rotary_dim, pos, theta); + const c = caches.paged(m, index); + // k rotated and rounded to the activation dtype as (kv_heads, rows, d), then with v into the pages from slot pos + const kr = try take(o, m.act, rows * s.kv_heads * hd); + try o.ropePrefill(kn, kr, rows * hd, hd, rows, s.kv_heads, hd, s.rotary_dim, pos, theta); + try o.pageWrite(kr.ptr, c.k, c.table, rows, s.kv_heads, hd, rows * hd, hd, pos, c.count); + try o.pageWrite(values.ptr, c.v, c.table, rows, s.kv_heads, hd, hd, s.kv_heads * hd, pos, c.count); + const att = try o.arena.of(f32, q_rows * hd); + try o.causalPaged(q32, c, att, rows, pos + rows, s.heads, scaleOf(hd), pos); + const gated = try take(o, m.act, q_rows * hd); + try o.attnGate(att, qg, gated, rows, s.heads, hd, false); + return o.project(gated, f.o, rows, f.o.partial); +} + +/// Linear attention: qkv, z, a, b, the conv over [state | rows], norms, gate, recurrence and the gated norm. +fn linear(o: Ops, m: *const view.Model, l: view.Linear, caches: *state.Caches, index: usize, x: Tensor, rows: usize) Error!Tensor { + const s = m.spec; + const qkv = try o.project(x, l.qkv, rows, false); + const z = try o.project(x, l.z, rows, false); + const a = try o.project(x, l.a, rows, false); + const b = try o.project(x, l.b, rows, false); + const cache = caches.layers[index].linear; + const ch = view.convChannels(s); + const mixed = try o.arena.of(f32, rows * ch); + // the new window lands beside the old one (every row reads the old), then replaces it + const conv_bytes = (s.conv - 1) * ch * 4; + const window = try o.arena.take(conv_bytes); + try o.convPrefill(qkv, l.conv, cache.conv.base(), mixed, window, rows, ch, s.conv); + try hip.raw.copy(cache.conv, 0, window, conv_bytes, o.stream); + const q, const k, const v = try splitQkv(o, m, .{ .ptr = mixed, .kind = .f32 }, rows); + const gate = try o.arena.of(f32, rows * s.value_heads); + const beta = try o.arena.of(f32, rows * s.value_heads); + try o.gdnGatePrefill(a, b, l.a_log, l.dt_bias, gate, beta, rows, s.value_heads); + const y = try o.arena.of(f32, rows * s.valueWidth()); + try o.gatedDelta(q, k, v, gate, beta, cache.state.base(), y, rows, s.key_heads, s.value_heads, s.key_dim, s.value_dim, null); + return gatedOut(o, m, l, y, z, rows); +} + +/// The conv output's q and k, normalized (fp32, contiguous), and v (fp32, contiguous). +pub fn splitQkv(o: Ops, m: *const view.Model, mixed: Tensor, rows: usize) Error!struct { u64, u64, u64 } { + const s = m.spec; + const kw = s.keyWidth(); + const ch = view.convChannels(s); + const qc = try o.arena.of(f32, rows * kw); + const kc = try o.arena.of(f32, rows * kw); + const v = try o.arena.of(f32, rows * s.valueWidth()); + try o.copyCols(mixed, ch, 0, qc, rows, kw); + try o.copyCols(mixed, ch, kw, kc, rows, kw); + try o.copyCols(mixed, ch, 2 * kw, v, rows, s.valueWidth()); + const q = try o.arena.of(f32, rows * kw); + const k = try o.arena.of(f32, rows * kw); + const heads = rows * s.key_heads; + try o.rms(.{ .ptr = qc, .kind = .f32 }, m.qk.q_weight, .{ .ptr = q, .kind = .f32 }, heads, s.key_dim, m.qk.eps); + try o.rms(.{ .ptr = kc, .kind = .f32 }, m.qk.k_weight, .{ .ptr = k, .kind = .f32 }, heads, s.key_dim, m.qk.eps); + return .{ q, k, v }; +} + +/// rms_norm(y, gnorm) * silu(z), rounded to the activation dtype, then the out projection. +pub fn gatedOut(o: Ops, m: *const view.Model, l: view.Linear, y: u64, z: Tensor, rows: usize) Error!Tensor { + const s = m.spec; + const n = rows * s.valueWidth(); + const out = try take(o, m.act, n); + if (o.fused() and s.value_dim <= 1024 and z.kind == m.act) { + try o.gnormOut(y, l.gnorm, z, out, rows * s.value_heads, s.value_dim, @floatCast(s.eps)); + } else { + const yn = try o.arena.of(f32, n); + try o.rms(.{ .ptr = y, .kind = .f32 }, l.gnorm, .{ .ptr = yn, .kind = .f32 }, rows * s.value_heads, s.value_dim, @floatCast(s.eps)); + try o.gnormSilu(yn, z, out, n); + } + return o.project(out, l.out, rows, l.out.partial); +} + +/// _mlp: gate and up, silu(gate) * up, down; or the routed experts (`prefill` is the span's length above one). +pub fn mlpRows(o: Ops, m: *const view.Model, mlp: view.Mlp, x: Tensor, rows: usize, prefill: bool) Error!Tensor { + switch (mlp) { + .moe => |r| return moe.run(o, m, r, x, rows, prefill and rows > 1), + .dense => |d| { + var outs: [4]Tensor = undefined; + const gate, const up = if (try o.projectGroup(x, &.{ d.gate, d.up }, rows, &outs)) + .{ outs[0], outs[1] } + else + .{ try o.project(x, d.gate, rows, false), try o.project(x, d.up, rows, false) }; + const act = try take(o, m.act, rows * d.gate.n); + try o.siluMul(gate, up, act, rows * d.gate.n); + return o.project(act, d.down, rows, d.down.partial); + }, + } +} diff --git a/zig/src/families/qwen3_5/backend/hip/forward/moe.zig b/zig/src/families/qwen3_5/backend/hip/forward/moe.zig new file mode 100644 index 00000000000..4825f72089c --- /dev/null +++ b/zig/src/families/qwen3_5/backend/hip/forward/moe.zig @@ -0,0 +1,123 @@ +//! The routed MoE of MLX affine experts: router, pick rule, plan, gate and up, activation, down, slots summed in order. + +const std = @import("std"); +const hip = @import("hip"); +const view = @import("../model/view.zig"); + +const Ops = hip.ops.Ops; +const Tensor = hip.ops.Tensor; + +/// experts.py: the decode tile's most rows, the GEMM tile's rows and where it starts, items' pair cap. +const LANE_ROWS = 8; +const BLOCK_ROWS = 128; +const BLOCK_FROM = 64; +const TILE = 16; + +/// MoEBuffers' size for `rows` rows: the next power of two from 16. +pub fn bucket(rows: usize) usize { + const bits = if (rows <= 1) 0 else std.math.log2_int_ceil(usize, rows); + return @as(usize, 1) << @intCast(@max(4, bits)); +} + +/// max_items(pairs, experts, min(TILE, LANE_ROWS)): an item a used expert plus one a tile of pairs past its first. +pub fn capacity(pairs: usize, experts: usize) usize { + return @min(pairs, experts) + pairs / @min(TILE, LANE_ROWS); +} + +/// tile_for: the decode tile below BLOCK_FROM rows, the GEMM tile from there; a lane round's rows keep the decode tile. +fn tileFor(o: Ops, rows: usize) usize { + return if (rows < BLOCK_FROM or o.window) LANE_ROWS else BLOCK_ROWS; +} + +/// `x` (rows, D) to (rows, D) in its dtype: the top-k experts plus the shared one; a tp rank returns its fp32 share. +pub fn run(o: Ops, m: *const view.Model, r: view.Routed, x: Tensor, rows: usize, prefill: bool) hip.ops.Error!Tensor { + _ = prefill; // the affine experts' arithmetic does not depend on it (the plan's tile comes from tile_for) + const ex = r.experts; + const slots = r.top_k + 1; + const size = bucket(rows); + const pairs = rows * slots; + const cap = capacity(size * slots, r.rows); + const logits = try o.arena.of(f32, rows * r.rows); + const pick = try o.arena.of(i32, size * slots); + const wts = try o.arena.of(f32, size * slots); + const items = try o.arena.of(i32, cap * 3); + const members = try o.arena.of(i32, size * slots); + try o.moeRouter(x, r.rows32, logits, rows, ex.dims, r.rows); + const count: usize = cap; + var tile: usize = undefined; + if (r.remap != 0) { + // every rank picks the same pairs, runs the ones it holds (the others group under an id past its experts) + try o.moeSelect(logits, pick, wts, null, 0, rows, r.count(), r.top_k); + const local = try o.arena.of(i32, size * slots); + try o.moeLocalize(pick, r.remap, local, pairs, ex.count); + tile = tileFor(o, rows); + try o.moeRoute(local, pairs, r.rows, tile, members, items, cap); + try o.moeForeignItems(items, cap, ex.count); + const both = try o.projectRouted(x, ex.fused, items, count, members, pairs, slots, @min(tile, rows)); + const act = try o.arena.take(pairs * ex.width * m.act.size()); + const act_t: Tensor = .{ .ptr = act, .kind = m.act }; + try o.moeAct(both, act_t, pairs, ex.width, ex.limit); + const y = try o.projectRouted(act_t, ex.down, items, count, members, pairs, 1, @min(tile, rows)); + try o.moeZeroForeign(y, local, ex.count, pairs, ex.dims); + const share = try o.arena.of(f32, rows * ex.dims); + try o.moeCombine(y, wts, .{ .ptr = share, .kind = .f32 }, rows, slots, ex.dims); + return .{ .ptr = share, .kind = .f32 }; + } + const p = try expertParts(o, m, r, x, rows, logits, pick, wts, items, members, cap); + const out = try o.arena.take(rows * ex.dims * m.act.size()); + try o.moeCombine(p.y, wts, .{ .ptr = out, .kind = m.act }, rows, slots, ex.dims); + return .{ .ptr = out, .kind = m.act }; +} + +/// The routed slots a row (fp32) and their weights before the sum: a single rank only. +pub const Parts = struct { y: u64, wts: u64, slots: usize }; + +pub fn parts(o: Ops, m: *const view.Model, r: view.Routed, x: Tensor, rows: usize) hip.ops.Error!Parts { + const slots = r.top_k + 1; + const size = bucket(rows); + const cap = capacity(size * slots, r.rows); + const logits = try o.arena.of(f32, rows * r.rows); + const pick = try o.arena.of(i32, size * slots); + const wts = try o.arena.of(f32, size * slots); + const items = try o.arena.of(i32, cap * 3); + const members = try o.arena.of(i32, size * slots); + try o.moeRouter(x, r.rows32, logits, rows, r.experts.dims, r.rows); + const p = try expertParts(o, m, r, x, rows, logits, pick, wts, items, members, cap); + return .{ .y = p.y, .wts = wts, .slots = slots }; +} + +/// Select, plan, gate and up, the activation and down: the rows' slots before the combine. +fn expertParts(o: Ops, m: *const view.Model, r: view.Routed, x: Tensor, rows: usize, logits: u64, pick: u64, wts: u64, items: u64, members: u64, cap: usize) hip.ops.Error!struct { y: u64 } { + const ex = r.experts; + const slots = r.top_k + 1; + const pairs = rows * slots; + var count: usize = cap; + var tile: usize = undefined; + if (rows == 1) { + try o.moeSelect(logits, pick, wts, .{ .items = items, .members = members }, cap, 1, r.count(), r.top_k); + tile = 1; + count = slots; + } else { + try o.moeSelect(logits, pick, wts, null, 0, rows, r.count(), r.top_k); + tile = tileFor(o, rows); + try o.moeRoute(pick, pairs, r.rows, tile, members, items, cap); + } + // the gate and up's activation is the launch's epilogue when the tile takes the shape + const act_t: Tensor = if (try o.projectRoutedAct(x, ex.fused, items, count, members, pairs, slots, @min(tile, rows), ex.limit)) |t| t else blk: { + const both = try o.projectRouted(x, ex.fused, items, count, members, pairs, slots, @min(tile, rows)); + const act = try o.arena.take(pairs * ex.width * m.act.size()); + const t: Tensor = .{ .ptr = act, .kind = m.act }; + try o.moeAct(both, t, pairs, ex.width, ex.limit); + break :blk t; + }; + const y = try o.projectRouted(act_t, ex.down, items, count, members, pairs, 1, @min(tile, rows)); + return .{ .y = y }; +} + +test "buffer sizes follow moe.run and max_items" { + try std.testing.expectEqual(@as(usize, 16), bucket(1)); + try std.testing.expectEqual(@as(usize, 16), bucket(16)); + try std.testing.expectEqual(@as(usize, 32), bucket(17)); + try std.testing.expectEqual(@as(usize, 2048), bucket(2048)); + try std.testing.expectEqual(@as(usize, 129 + 16 * 9 / 8), capacity(16 * 9, 129)); +} diff --git a/zig/src/families/qwen3_5/backend/hip/forward/pages.zig b/zig/src/families/qwen3_5/backend/hip/forward/pages.zig new file mode 100644 index 00000000000..5866102974f --- /dev/null +++ b/zig/src/families/qwen3_5/backend/hip/forward/pages.zig @@ -0,0 +1,216 @@ +//! Paged KV: attention keys and values in a pool of reference-counted pages, so streams and the prefix tree share them. + +const std = @import("std"); +const hip = @import("hip"); +const view = @import("../model/view.zig"); +const Allocator = std.mem.Allocator; + +/// Positions a page holds: the chunk of the recurrence, so a page edge is a chunk edge. +pub const tokens = 64; + +/// Pages that hold `n` positions. +pub fn pagesFor(n: usize) usize { + return (n + tokens - 1) / tokens; +} + +/// Which page ids are free and how many holders each has: host bookkeeping only. +pub const Ids = struct { + refs: []u32, + free: std.ArrayList(u32) = .empty, + /// Pages promised to streams that have not taken them yet. + reserved: usize = 0, + + pub fn init(gpa: Allocator, count: usize) !Ids { + const refs = try gpa.alloc(u32, count); + errdefer gpa.free(refs); + @memset(refs, 0); + var ids: Ids = .{ .refs = refs }; + errdefer ids.free.deinit(gpa); + try ids.free.ensureTotalCapacity(gpa, count); + // the lowest id is taken first + var i: u32 = @intCast(count); + while (i > 0) { + i -= 1; + ids.free.appendAssumeCapacity(i); + } + return ids; + } + + pub fn deinit(ids: *Ids, gpa: Allocator) void { + ids.free.deinit(gpa); + gpa.free(ids.refs); + } + + /// A free page, now held once; null when none is free. + pub fn take(ids: *Ids) ?u32 { + const id = ids.free.pop() orelse return null; + ids.refs[id] = 1; + return id; + } + + pub fn retain(ids: *Ids, id: u32) void { + std.debug.assert(ids.refs[id] > 0); + ids.refs[id] += 1; + } + + /// One holder less; the page is free again when none is left. + pub fn release(ids: *Ids, id: u32) void { + std.debug.assert(ids.refs[id] > 0); + ids.refs[id] -= 1; + if (ids.refs[id] == 0) ids.free.appendAssumeCapacity(id); + } + + /// Pages free and not promised. + pub fn available(ids: *const Ids) usize { + return ids.free.items.len -| ids.reserved; + } + + pub fn used(ids: *const Ids) usize { + return ids.refs.len - ids.free.items.len; + } +}; + +/// Each attention layer's key and value pools and their ids: `kv_heads` runs of `count` pages, contiguous in order. +pub const Pool = struct { + gpa: Allocator, + d: *const hip.Runtime, + count: usize, + kv_heads: usize, + head_dim: usize, + act_bytes: usize, + /// A layer's keys and values: empty buffers for a linear layer. + keys: []hip.DeviceBuffer, + values: []hip.DeviceBuffer, + ids: Ids, + /// Whether this holder hands pages out (rank 0 and a lone rank); a follower is told which pages to use. + managed: bool, + + /// Device bytes a pool of `count` pages holds: keys and values of every attention layer. + pub fn deviceBytes(m: *const view.Model, count: usize) usize { + const s = m.spec; + var full: usize = 0; + for (0..s.n_layers) |i| full += @intFromBool(s.full(i)); + return 2 * full * count * s.kv_heads * tokens * s.head_dim * m.act.size(); + } + + pub fn init(gpa: Allocator, d: *const hip.Runtime, m: *const view.Model, count: usize, managed: bool) !Pool { + const s = m.spec; + const keys = try gpa.alloc(hip.DeviceBuffer, s.n_layers); + errdefer gpa.free(keys); + const values = try gpa.alloc(hip.DeviceBuffer, s.n_layers); + errdefer gpa.free(values); + var made: usize = 0; + errdefer for (0..made) |i| { + keys[i].free(); + values[i].free(); + }; + const per_layer = count * s.kv_heads * tokens * s.head_dim * m.act.size(); + for (0..s.n_layers) |i| { + const bytes = if (s.full(i)) per_layer else 0; + keys[i] = try hip.DeviceBuffer.alloc(d, bytes); + errdefer keys[i].free(); + values[i] = try hip.DeviceBuffer.alloc(d, bytes); + made += 1; + } + return .{ .gpa = gpa, .d = d, .count = count, .kv_heads = s.kv_heads, .head_dim = s.head_dim, .act_bytes = m.act.size(), .keys = keys, .values = values, .ids = try Ids.init(gpa, count), .managed = managed }; + } + + pub fn deinit(p: *Pool) void { + p.ids.deinit(p.gpa); + for (p.keys, p.values) |*k, *v| { + k.free(); + v.free(); + } + p.gpa.free(p.keys); + p.gpa.free(p.values); + } + + /// Bytes of one position's keys and values of a layer. + fn rowBytes(p: *const Pool) usize { + return p.head_dim * p.act_bytes; + } + + /// Bytes of one head's share of a page of one layer's keys (or values). + fn headBytes(p: *const Pool) usize { + return tokens * p.rowBytes(); + } + + /// Bytes of one page of one layer's keys (or values), over its heads. + pub fn layerBytes(p: *const Pool) usize { + return p.kv_heads * p.headBytes(); + } + + /// Bytes of a page over every attention layer, keys and values. + pub fn pageBytes(p: *const Pool) usize { + var layers: usize = 0; + for (p.keys) |k| layers += @intFromBool(k.len > 0); + return 2 * layers * p.layerBytes(); + } + + /// A page for one holder, or null when the pool has none. + pub fn take(p: *Pool) ?u32 { + return p.ids.take(); + } + + pub fn retain(p: *Pool, id: u32) void { + if (p.managed) p.ids.retain(id); + } + + pub fn release(p: *Pool, id: u32) void { + if (p.managed) p.ids.release(id); + } + + /// Copies page `from` into page `to` in every layer. + pub fn copyPage(p: *Pool, from: u32, to: u32, stream: hip.abi.Stream) !void { + if (from >= p.count or to >= p.count) return error.BadPage; + const n = p.headBytes(); + for (p.keys, p.values) |k, v| { + if (k.len == 0) continue; + for (0..p.kv_heads) |h| { + const run = h * p.count * n; + try hip.raw.copy(k, run + to * n, k.base() + run + from * n, n, stream); + try hip.raw.copy(v, run + to * n, v.base() + run + from * n, n, stream); + } + } + } + + /// Page `id`'s keys of layer `layer` read back, then its values, each head after head: for checks. + pub fn read(p: *const Pool, layer: usize, id: u32, out: []u8) !void { + const n = p.headBytes(); + std.debug.assert(out.len == 2 * p.layerBytes()); + for (0..p.kv_heads) |h| { + try p.keys[layer].download((h * p.count + id) * n, out[h * n ..][0..n]); + try p.values[layer].download((h * p.count + id) * n, out[(p.kv_heads + h) * n ..][0..n]); + } + } +}; + +test "ids hand out the lowest page and free it when its last holder lets go" { + var ids = try Ids.init(std.testing.allocator, 3); + defer ids.deinit(std.testing.allocator); + try std.testing.expectEqual(@as(?u32, 0), ids.take()); + try std.testing.expectEqual(@as(?u32, 1), ids.take()); + ids.retain(0); + ids.release(0); + try std.testing.expectEqual(@as(usize, 1), ids.available()); + ids.release(0); + try std.testing.expectEqual(@as(usize, 2), ids.available()); + try std.testing.expectEqual(@as(?u32, 0), ids.take()); + try std.testing.expectEqual(@as(?u32, 2), ids.take()); + try std.testing.expectEqual(@as(?u32, null), ids.take()); +} + +test "reserved pages are not available" { + var ids = try Ids.init(std.testing.allocator, 4); + defer ids.deinit(std.testing.allocator); + ids.reserved = 3; + try std.testing.expectEqual(@as(usize, 1), ids.available()); + ids.reserved = 9; + try std.testing.expectEqual(@as(usize, 0), ids.available()); +} + +test "pages cover positions by 64" { + try std.testing.expectEqual(@as(usize, 0), pagesFor(0)); + try std.testing.expectEqual(@as(usize, 1), pagesFor(64)); + try std.testing.expectEqual(@as(usize, 2), pagesFor(65)); +} diff --git a/zig/src/families/qwen3_5/backend/hip/forward/plan.zig b/zig/src/families/qwen3_5/backend/hip/forward/plan.zig new file mode 100644 index 00000000000..a73a1b17733 --- /dev/null +++ b/zig/src/families/qwen3_5/backend/hip/forward/plan.zig @@ -0,0 +1,141 @@ +//! A lane round's plan on the device; launches depend only on its `Shape`, so one graph serves any streams and caches. + +const std = @import("std"); +const hip = @import("hip"); +const state = @import("state.zig"); + +const round_shape = @import("round_shape.zig"); + +pub const buckets = round_shape.buckets; +pub const min_span = round_shape.min_span; +pub const bucketOf = round_shape.bucketOf; +pub const spanOf = round_shape.spanOf; +pub const Shape = round_shape.Shape; + +/// Where each array sits in the plan buffer, in 4-byte words (the 8-byte arrays on even words). +pub const Layout = struct { + layers: usize, + tokens: usize, + pos: usize, + slot: usize, + first: usize, + count: usize, + keep: usize, + desc: usize, + snaps: usize, + words: usize, + + pub fn of(rows: usize, slots: usize, layers: usize) Layout { + var l: Layout = undefined; + l.layers = layers; + l.tokens = 0; + l.pos = rows; + l.slot = 2 * rows; + l.first = 3 * rows; + l.count = l.first + slots; + l.keep = l.count + slots; + l.desc = std.mem.alignForward(usize, l.keep + slots, 2); + l.snaps = l.desc + 2 * slots; + l.words = l.snaps + 4 * layers; + return l; + } +}; + +fn put64(w: []u32, v: u64) void { + w[0] = @truncate(v); + w[1] = @truncate(v >> 32); +} + +/// One stream's window of a round: its descriptor, the slot its first row takes, its tokens. +pub const Window = struct { desc: u64, pos: usize, tokens: []const u32 }; + +/// The plan buffer of one engine, as large as its biggest round, and the pinned words a round is written in. +pub const Buffer = struct { + host: hip.HostBuffer, + dev: hip.DeviceBuffer, + /// Pages a head of a layer's pool holds: the kernels find a page's keys and values with it. + pool_pages: u32, + + /// Device bytes a plan of `rows` rows over `layers` layers holds. + pub fn deviceBytes(rows: usize, layers: usize) usize { + return 4 * Layout.of(rows, rows + 1, layers).words; + } + + pub fn init(d: *const hip.Runtime, rows: usize, layers: usize, pool_pages: usize) !Buffer { + const bytes = deviceBytes(rows, layers); + var host = try hip.HostBuffer.alloc(d, bytes); + errdefer host.free(); + return .{ .host = host, .dev = try hip.DeviceBuffer.alloc(d, bytes), .pool_pages = @intCast(pool_pages) }; + } + + pub fn deinit(b: *Buffer) void { + b.dev.free(); + b.host.free(); + } + + /// The device words of `shape` as launches read them. + pub fn args(b: *const Buffer, l: Layout) hip.plan_ops.Args { + const at = b.dev.base(); + return .{ + .pos = at + 4 * l.pos, + .slot = at + 4 * l.slot, + .first = at + 4 * l.first, + .count = at + 4 * l.count, + .desc = at + 4 * l.desc, + .snaps = at + 4 * l.snaps, + .pages = @intCast(state.header_words + 2 * l.layers), + .pool = b.pool_pages, + }; + } + + /// Writes the round into the pinned words: windows, the scratch slot's `pad` rows, each linear layer's snapshots. + pub fn fill(b: *Buffer, l: Layout, shape: Shape, windows: []const Window, scratch: u64, snaps: []const [2]u64) void { + const w = b.host.slice(u32); + const slots: usize = shape.slots; + var at: usize = 0; + for (windows, 0..) |win, s| { + w[l.first + s] = @intCast(at); + w[l.count + s] = @intCast(win.tokens.len); + w[l.keep + s] = std.math.maxInt(u32); + put64(w[l.desc + 2 * s ..], win.desc); + for (win.tokens, 0..) |t, i| { + w[l.tokens + at + i] = t; + w[l.pos + at + i] = @intCast(win.pos + i); + w[l.slot + at + i] = @intCast(s); + } + at += win.tokens.len; + } + // slots past the streams' are empty and the last is the scratch slot, where padding rows run from its start + for (windows.len..slots - 1) |s| { + w[l.first + s] = 0; + w[l.count + s] = 0; + w[l.keep + s] = std.math.maxInt(u32); + put64(w[l.desc + 2 * s ..], 0); + } + const pad = shape.rows - at; + w[l.first + slots - 1] = @intCast(at); + w[l.count + slots - 1] = @intCast(pad); + w[l.keep + slots - 1] = std.math.maxInt(u32); + put64(w[l.desc + 2 * (slots - 1) ..], scratch); + for (0..pad) |i| { + w[l.tokens + at + i] = 0; + w[l.pos + at + i] = @intCast(i); + w[l.slot + at + i] = @intCast(slots - 1); + } + for (snaps, 0..) |pair, i| { + put64(w[l.snaps + 4 * i ..], pair[0]); + put64(w[l.snaps + 4 * i + 2 ..], pair[1]); + } + } + + /// The filled words up to the device in one copy (a graph holds the copy: it runs from the same pinned words). + pub fn send(b: *const Buffer, stream: hip.abi.Stream, l: Layout) !void { + try hip.raw.upload(b.dev, 0, b.host.bytes[0 .. 4 * l.words], stream); + } +}; + +test "layout keeps the eight-byte arrays on even words" { + const l = Layout.of(5, 4, 3); + try std.testing.expect(l.desc % 2 == 0 and l.snaps % 2 == 0); + try std.testing.expect(l.words >= l.snaps + 12); +} diff --git a/zig/src/families/qwen3_5/backend/hip/forward/reduce.zig b/zig/src/families/qwen3_5/backend/hip/forward/reduce.zig new file mode 100644 index 00000000000..7e20ac30113 --- /dev/null +++ b/zig/src/families/qwen3_5/backend/hip/forward/reduce.zig @@ -0,0 +1,38 @@ +//! The tensor-parallel reduce: ranks' fp32 shares summed before each residual add, logits slices joined in rank order. + +const std = @import("std"); +const hip = @import("hip"); +const view = @import("../model/view.zig"); + +const Ops = hip.ops.Ops; +const Tensor = hip.ops.Tensor; + +pub const Error = hip.ops.Error || hip.collective.Error; + +/// `n` fp32 values summed over the ranks in rank order, so a row's sum does not depend on the rows sharing the call. +pub fn sum(o: Ops, c: hip.collective.Comm, y: u64, n: usize) Error!u64 { + const out = try o.arena.of(f32, n); + if (c.world == 2) { + try c.allReduce(y, out, n, .f32, o.stream); + return out; + } + const parts = try o.arena.of(f32, c.world * n); + try c.allGather(y, parts, n, .f32, o.stream); + const part = n * 4; + try o.add(.{ .ptr = parts, .kind = .f32 }, .{ .ptr = parts + part, .kind = .f32 }, .{ .ptr = out, .kind = .f32 }, n); + for (2..c.world) |r| try o.add(.{ .ptr = out, .kind = .f32 }, .{ .ptr = parts + r * part, .kind = .f32 }, .{ .ptr = out, .kind = .f32 }, n); + return out; +} + +/// x += y on the residual rows: an activation-dtype `y` as one rank adds it, an fp32 share summed over the ranks first. +pub fn residual(o: Ops, m: *const view.Model, x: Tensor, y: Tensor, n: usize) Error!void { + if (y.kind != .f32) return o.add(x, y, x, n); + const total = try sum(o, m.tp.?, y.ptr, n); + try o.addWide(x, total, x, n); +} + +/// The ranks' logits slices (world, rows, width) of the activation dtype, gathered into `out`. +pub fn gather(o: Ops, c: hip.collective.Comm, slice: Tensor, out: u64, n: usize) Error!void { + const dtype: hip.collective.Dtype = if (slice.kind == .f16) .f16 else .bf16; + try c.allGather(slice.ptr, out, n, dtype, o.stream); +} diff --git a/zig/src/families/qwen3_5/backend/hip/forward/round_shape.zig b/zig/src/families/qwen3_5/backend/hip/forward/round_shape.zig new file mode 100644 index 00000000000..6e11bd93cbb --- /dev/null +++ b/zig/src/families/qwen3_5/backend/hip/forward/round_shape.zig @@ -0,0 +1,37 @@ +//! What a lane round's launches depend on, so a graph captured for a shape replays for any streams of that shape. + +const std = @import("std"); + +/// Rows a round runs are padded up to one of these (and the limit), so the shapes stay few. +pub const buckets = [_]usize{ 1, 2, 4, 8, 16, 32, 64 }; + +/// Shortest span the attention walk covers; spans double from here. +pub const min_span = 128; + +/// The rows a round of `rows` real rows runs: the smallest bucket that holds them, the limit past the last bucket. +pub fn bucketOf(rows: usize, limit: usize) usize { + for (buckets) |b| if (b >= rows) return @min(b, limit); + return limit; +} + +/// The keys the attention walk covers when the longest row sees `visible`: min_span doubled until it holds them. +pub fn spanOf(visible: usize) usize { + var span: usize = min_span; + while (span < visible) span *= 2; + return span; +} + +/// A round's rows (padding included), slots (streams', empties to a bucket, then the padding's scratch slot) and keys. +pub const Shape = struct { + rows: u32, + slots: u32, + span: u32, +}; + +test "buckets round up and the span doubles" { + try std.testing.expectEqual(@as(usize, 4), bucketOf(3, 64)); + try std.testing.expectEqual(@as(usize, 32), bucketOf(17, 32)); + try std.testing.expectEqual(@as(usize, 6), bucketOf(5, 6)); + try std.testing.expectEqual(@as(usize, 128), spanOf(1)); + try std.testing.expectEqual(@as(usize, 512), spanOf(300)); +} diff --git a/zig/src/families/qwen3_5/backend/hip/forward/state.zig b/zig/src/families/qwen3_5/backend/hip/forward/state.zig new file mode 100644 index 00000000000..e3afdd1c88e --- /dev/null +++ b/zig/src/families/qwen3_5/backend/hip/forward/state.zig @@ -0,0 +1,257 @@ +//! A stream's device caches: its page table over the attention pools, and each linear layer's conv window and state. + +const std = @import("std"); +const hip = @import("hip"); +const view = @import("../model/view.zig"); +const pages = @import("pages.zig"); +const Allocator = std.mem.Allocator; + +pub const LayerCache = union(enum) { + /// The keys and values are in the pool's pages. + full, + linear: struct { conv: hip.DeviceBuffer, state: hip.DeviceBuffer }, +}; + +/// Words of a descriptor before its layers: the positions it holds and the last kept final row. +pub const header_words = 2; + +pub const Caches = struct { + layers: []LayerCache, + /// Positions the page table can name. + total: usize, + /// Kernel view: positions, last kept final row (0 until `setHidden`), two addresses a layer, then the page table. + desc: hip.DeviceBuffer, + pool: *pages.Pool, + /// The page table as the device holds it: the pages of the first positions, each held once by this stream. + table: std.ArrayList(u32) = .empty, + /// Pages promised to this stream, not yet taken (the pool's reservation). + promised: usize = 0, + + /// Device bytes the caches of `total` positions hold beside their pages: linear state and the descriptor. + pub fn deviceBytes(m: *const view.Model, total: usize) usize { + const s = m.spec; + var linear: usize = 0; + for (0..s.n_layers) |i| linear += @intFromBool(!s.full(i)); + const conv = (s.conv - 1) * view.convChannels(s) * 4; + const state = s.value_heads * s.value_dim * s.key_dim * 4; + return linear * (conv + state) + 8 * (header_words + 2 * s.n_layers + std.mem.alignForward(usize, pages.pagesFor(total), 2) / 2); + } + + /// Caches for up to `total` positions with no pages yet; every linear byte zeroed. + pub fn init(gpa: Allocator, pool: *pages.Pool, m: *const view.Model, total: usize) !Caches { + const d = pool.d; + const s = m.spec; + const layers = try gpa.alloc(LayerCache, s.n_layers); + var made: usize = 0; + errdefer { + for (layers[0..made]) |*l| free(l); + gpa.free(layers); + } + for (layers, 0..) |*l, i| { + if (s.full(i)) { + l.* = .full; + } else { + var conv = try hip.DeviceBuffer.alloc(d, (s.conv - 1) * view.convChannels(s) * 4); + errdefer conv.free(); + var state = try hip.DeviceBuffer.alloc(d, s.value_heads * s.value_dim * s.key_dim * 4); + errdefer state.free(); + try conv.fill8(0); + try state.fill8(0); + l.* = .{ .linear = .{ .conv = conv, .state = state } }; + } + made += 1; + } + const slots = std.mem.alignForward(usize, pages.pagesFor(total), 2); + const words = try gpa.alloc(u64, header_words + 2 * s.n_layers + slots / 2); + defer gpa.free(words); + @memset(words, 0); + var desc = try hip.DeviceBuffer.alloc(d, 8 * words.len); + errdefer desc.free(); + words[0] = total; + for (layers, 0..) |l, i| switch (l) { + .full => words[header_words + 2 * i ..][0..2].* = .{ pool.keys[i].base(), pool.values[i].base() }, + .linear => |x| words[header_words + 2 * i ..][0..2].* = .{ x.conv.base(), x.state.base() }, + }; + try desc.upload(0, std.mem.sliceAsBytes(words)); + return .{ .layers = layers, .total = total, .desc = desc, .pool = pool }; + } + + /// Caches for `total` positions with every page taken now (a check or a timing, with no reservation to keep). + pub fn initFull(gpa: Allocator, pool: *pages.Pool, m: *const view.Model, total: usize) !Caches { + var c = try init(gpa, pool, m, total); + errdefer c.deinit(gpa); + _ = try c.grow(gpa, total); + return c; + } + + /// The stream's last kept final row lives at `ptr`: a round's keep copies it there. + pub fn setHidden(c: *const Caches, ptr: u64) !void { + try c.desc.upload(8, std.mem.asBytes(&ptr)); + } + + fn free(l: *LayerCache) void { + switch (l.*) { + .full => {}, + .linear => |*x| { + x.conv.free(); + x.state.free(); + }, + } + } + + /// Hands every page back (to the tree and the other streams that hold them, or to the pool) and frees the buffers. + pub fn deinit(c: *Caches, gpa: Allocator) void { + for (c.table.items) |id| c.pool.release(id); + c.pool.ids.reserved -|= c.promised; + c.table.deinit(gpa); + c.desc.free(); + for (c.layers) |*l| free(l); + gpa.free(c.layers); + c.* = undefined; + } + + /// Positions the pages cover. + pub fn covered(c: *const Caches) usize { + return @min(c.table.items.len * pages.tokens, c.total); + } + + /// Bytes this stream holds: its linear state and every page it names (shared ones counted whole). + pub fn held(c: *const Caches) usize { + var n: usize = c.table.items.len * c.pool.pageBytes(); + for (c.layers) |l| switch (l) { + .full => {}, + .linear => |x| n += x.conv.len + x.state.len, + }; + return n; + } + + fn put(c: *const Caches, first: usize, ids: []const u32) !void { + const base = 8 * (header_words + 2 * c.layers.len); + try c.desc.upload(base + 4 * first, std.mem.sliceAsBytes(ids)); + } + + /// Takes pages until `n` positions are covered, counted against any promise; new ids valid until the next call. + pub fn grow(c: *Caches, gpa: Allocator, n: usize) ![]const u32 { + const want = pages.pagesFor(@min(n, c.total)); + const first = c.table.items.len; + if (want <= first) return c.table.items[first..]; + try c.table.ensureTotalCapacity(gpa, want); + errdefer c.table.shrinkRetainingCapacity(first); + while (c.table.items.len < want) c.table.appendAssumeCapacity(c.pool.take() orelse return error.OutOfPages); + const taken = want - first; + const own = @min(c.promised, taken); + c.promised -= own; + c.pool.ids.reserved -|= own; + try c.put(first, c.table.items[first..]); + return c.table.items[first..]; + } + + /// Sets the table from page `at` to `ids`; the caller's references move into it and replaced pages are released. + pub fn set(c: *Caches, gpa: Allocator, at: usize, ids: []const u32) !void { + try c.table.ensureTotalCapacity(gpa, at + ids.len); + for (ids, at..) |id, i| { + if (i < c.table.items.len) { + if (c.table.items[i] == id) { + c.pool.release(id); + continue; + } + c.pool.release(c.table.items[i]); + c.table.items[i] = id; + } else { + std.debug.assert(i == c.table.items.len); + c.table.appendAssumeCapacity(id); + } + } + try c.put(at, c.table.items[at..][0..ids.len]); + } + + /// Copies each shared page holding positions `from .. to`; `out` gets its table index, old and new page. + pub fn writable(c: *Caches, out: *std.ArrayList([3]u32), gpa: Allocator, from: usize, to: usize, stream: hip.abi.Stream) !void { + var i = from / pages.tokens; + const last = @min(pages.pagesFor(to), c.table.items.len); + while (i < last) : (i += 1) { + const old = c.table.items[i]; + if (c.pool.ids.refs[old] < 2) continue; + const fresh = c.pool.take() orelse return error.OutOfPages; + errdefer c.pool.release(fresh); + try c.pool.copyPage(old, fresh, stream); + c.table.items[i] = fresh; + c.pool.release(old); + try c.put(i, c.table.items[i..][0..1]); + try out.append(gpa, .{ @intCast(i), old, fresh }); + } + } + + /// The attention kernels' view of a full layer's pages. + pub fn paged(c: *const Caches, m: *const view.Model, index: usize) hip.ops.Ops.Paged { + const base = c.desc.base() + 8 * (header_words + 2 * c.layers.len); + return .{ .k = c.pool.keys[index].base(), .v = c.pool.values[index].base(), .table = base, .kind = m.act, .kv_heads = m.spec.kv_heads, .d = m.spec.head_dim, .count = c.pool.count }; + } + + /// Bytes of the linear layers' state. + pub fn linearBytes(c: *const Caches) usize { + var n: usize = 0; + for (c.layers) |l| switch (l) { + .full => {}, + .linear => |x| n += x.conv.len + x.state.len, + }; + return n; + } +}; + +/// A stream's linear state at a prompt's page edge: each linear layer's conv window and DeltaNet state, in tree slots. +pub const Snapshots = struct { + gpa: Allocator, + d: *const hip.Runtime, + slots: std.ArrayList(?hip.DeviceBuffer) = .empty, + + pub fn init(gpa: Allocator, d: *const hip.Runtime) Snapshots { + return .{ .gpa = gpa, .d = d }; + } + + pub fn deinit(s: *Snapshots) void { + for (s.slots.items) |*b| if (b.*) |*x| x.free(); + s.slots.deinit(s.gpa); + } + + /// Frees every slot's buffer. + pub fn clear(s: *Snapshots) void { + for (s.slots.items) |*b| if (b.*) |*x| x.free(); + s.slots.clearRetainingCapacity(); + } + + /// The caches' linear state copied into slot `slot` (its buffer made on first use). + pub fn take(s: *Snapshots, slot: u32, c: *const Caches, stream: hip.abi.Stream) !void { + while (s.slots.items.len <= slot) try s.slots.append(s.gpa, null); + const entry = &s.slots.items[slot]; + if (entry.* == null) entry.* = try hip.DeviceBuffer.alloc(s.d, c.linearBytes()); + var at: usize = 0; + for (c.layers) |l| switch (l) { + .full => {}, + .linear => |x| for ([_]hip.DeviceBuffer{ x.conv, x.state }) |b| { + try hip.raw.copy(entry.*.?, at, b.base(), b.len, stream); + at += b.len; + }, + }; + } + + /// Slot `slot`'s linear state copied back into the caches. + pub fn put(s: *const Snapshots, slot: u32, c: *Caches, stream: hip.abi.Stream) !void { + const buf = (if (slot < s.slots.items.len) s.slots.items[slot] else null) orelse return error.NoSnapshot; + var at: usize = 0; + for (c.layers) |l| switch (l) { + .full => {}, + .linear => |x| for ([_]hip.DeviceBuffer{ x.conv, x.state }) |b| { + try hip.raw.copy(b, 0, buf.base() + at, b.len, stream); + at += b.len; + }, + }; + } + + /// Bytes the slots hold. + pub fn held(s: *const Snapshots) usize { + var n: usize = 0; + for (s.slots.items) |b| n += if (b) |x| x.len else 0; + return n; + } +}; diff --git a/zig/src/families/qwen3_5/backend/hip/forward/window.zig b/zig/src/families/qwen3_5/backend/hip/forward/window.zig new file mode 100644 index 00000000000..46e0e6ac28f --- /dev/null +++ b/zig/src/families/qwen3_5/backend/hip/forward/window.zig @@ -0,0 +1,173 @@ +//! A lane round's forward: every stream's window in one pass over the round's device plan, each row bitwise serial. + +const std = @import("std"); +const hip = @import("hip"); +const view = @import("../model/view.zig"); +const fwd = @import("forward.zig"); +const moe = @import("moe.zig"); + +const Ops = hip.ops.Ops; +const Tensor = hip.ops.Tensor; +const pops = hip.plan_ops; + +/// A round's launches: the device plan, its token ids, the keys the attention walk covers, each layer's kept inputs. +pub const Round = struct { plan: pops.Plan, tokens: u64, span: usize, inputs: []const [2]u64 }; + +/// Whether this build and model run lane rounds: the merged decode launches, and shapes the plan kernels take. +pub fn supported(o: Ops, m: *const view.Model) bool { + const s = m.spec; + return o.fused() and s.key_dim <= 1024 and s.conv <= 8 and (s.key_dim == 128 or s.key_dim == 16) and s.value_dim % 8 == 0 and s.head_dim <= 256 and m.act != .f32; +} + +/// A linear layer's inputs a keep replays, `rows` rows: the conv inputs, then k, v, gate and beta; zero for attention. +pub fn kept(o: Ops, m: *const view.Model, rows: usize, table: [][2]u64) !void { + const s = m.spec; + for (table, 0..) |*t, index| { + t.* = .{ 0, 0 }; + if (s.full(index)) continue; + t[0] = try o.arena.of(f32, rows * view.convChannels(s)); + t[1] = try o.arena.of(f32, rows * (s.keyWidth() + s.valueWidth() + 2 * s.value_heads)); + } +} + +/// The final-normed rows of the round, in order (rows, hidden), padding rows included. +pub fn forward(ops: Ops, m: *const view.Model, r: Round, trace: ?fwd.Trace) fwd.Error!Tensor { + // a round's rows keep their decode kernels however many share it + var o = ops; + o.window = true; + const s = m.spec; + const total = r.plan.rows; + const x = try fwd.take(o, m.act, total * s.hidden); + try o.embedRows(m.embed, r.tokens, total, x); + const normed = try fwd.take(o, m.act, total * s.hidden); + const out = try fwd.take(o, m.act, total * s.hidden); + const eps: f32 = @floatCast(s.eps); + try o.rms(x, inputNorm(m.layers[0]), normed, total, s.hidden, eps); + for (m.layers, 0..) |layer, index| { + const mark = o.arena.mark(); + defer o.arena.release(mark); + const post_norm, const mlp = switch (layer) { + .full => |f| .{ f.post_norm, f.mlp }, + .linear => |l| .{ l.post_norm, l.mlp }, + }; + const y = switch (layer) { + .full => |f| try attentionRows(o, m, f, r, index, normed), + .linear => |l| try linearRows(o, m, l, r, index, normed), + }; + // the launches of a layer's two tails merge when the rows stay on this rank + const merge = o.fused() and y.kind == m.act; + const last = index + 1 == m.layers.len; + const next_norm = if (last) m.final_norm else inputNorm(m.layers[index + 1]); + const dest = if (last) out else normed; + if (merge) { + try o.addRms(x, y, post_norm, normed, total, s.hidden, eps); + } else { + try fwd.residual(o, m, x, y, total * s.hidden); + try o.rms(x, post_norm, normed, total, s.hidden, eps); + } + switch (mlp) { + .moe => |rt| if (merge and rt.remap == 0) { + const parts = try moe.parts(o, m, rt, normed, total); + try o.moeTail(x, parts.y, parts.wts, next_norm, dest, total, parts.slots, s.hidden, eps); + } else { + const z = try fwd.mlpRows(o, m, mlp, normed, total, true); + try fwd.residual(o, m, x, z, total * s.hidden); + try o.rms(x, next_norm, dest, total, s.hidden, eps); + }, + .dense => { + const z = try fwd.mlpRows(o, m, mlp, normed, total, true); + if (merge and z.kind == m.act) { + try o.addRms(x, z, next_norm, dest, total, s.hidden, eps); + } else { + try fwd.residual(o, m, x, z, total * s.hidden); + try o.rms(x, next_norm, dest, total, s.hidden, eps); + } + }, + } + if (trace) |t| t.layer(t.ctx, index, x, total) catch return error.HipFailed; + } + return out; +} + +fn inputNorm(layer: view.Layer) u64 { + return switch (layer) { + .full => |f| f.input_norm, + .linear => |l| l.input_norm, + }; +} + +/// Keeps the slots `counts` lists (negative: none): linear layers replay their kept rows, `hidden` gets the last. +pub fn keep(o: Ops, m: *const view.Model, p: pops.Plan, counts: u64, hidden: u64) hip.ops.Error!void { + const s = m.spec; + try pops.keep(o, p, .{ + .keep = counts, + .hidden = hidden, + .hidden_words = s.hidden * m.act.size() / 4, + .channels = view.convChannels(s), + .taps = s.conv - 1, + .layers = s.n_layers, + }); + try pops.gdnReplay(o, counts, p, s.key_heads, s.value_heads, s.key_dim, s.value_dim, s.n_layers); +} + +fn attentionRows(o: Ops, m: *const view.Model, f: view.Full, r: Round, index: usize, x: Tensor) fwd.Error!Tensor { + const s = m.spec; + const hd = s.head_dim; + const total = r.plan.rows; + var outs: [4]Tensor = undefined; + const qg, const keys, const values = if (try o.projectGroup(x, &.{ f.q, f.k, f.v }, total, &outs)) + .{ outs[0], outs[1], outs[2] } + else + .{ try o.project(x, f.q, total, false), try o.project(x, f.k, total, false), try o.project(x, f.v, total, false) }; + const q_rows = total * s.heads; + const eps: f32 = @floatCast(s.eps); + const theta: f32 = @floatCast(s.rope_theta); + // q and k normed, rotated and rounded in one launch; k then goes with v into the slots' caches + const q32 = try o.arena.of(f32, q_rows * hd); + try o.qkRope(qg, s.heads * 2 * hd, 2 * hd, f.q_norm, eps, total, s.heads, hd, s.rotary_dim, theta, r.plan.args.pos, q32, null, 0); + const k32 = try o.arena.of(f32, total * s.kv_heads * hd); + try o.qkRope(keys, s.kv_heads * hd, hd, f.k_norm, eps, total, s.kv_heads, hd, s.rotary_dim, theta, r.plan.args.pos, k32, null, 0); + try pops.kvWrite(o, k32, values, r.plan, index, s.kv_heads, hd); + const att = try o.arena.of(f32, q_rows * hd); + try pops.causal(o, q32, m.act, att, r.plan, index, s.heads, s.kv_heads, hd, r.span, fwd.scaleOf(hd)); + const gated = try fwd.take(o, m.act, q_rows * hd); + try o.attnGate(att, qg, gated, total, s.heads, hd, true); + return o.project(gated, f.o, total, f.o.partial); +} + +fn linearRows(o: Ops, m: *const view.Model, l: view.Linear, r: Round, index: usize, x: Tensor) fwd.Error!Tensor { + const s = m.spec; + const total = r.plan.rows; + var outs: [4]Tensor = undefined; + const qkv, const z, const a, const b = if (try o.projectGroup(x, &.{ l.qkv, l.z, l.a, l.b }, total, &outs)) + .{ outs[0], outs[1], outs[2], outs[3] } + else + .{ try o.project(x, l.qkv, total, false), try o.project(x, l.z, total, false), try o.project(x, l.a, total, false), try o.project(x, l.b, total, false) }; + const ch = view.convChannels(s); + const y = try o.arena.of(f32, total * s.valueWidth()); + // the k, v, gate and beta a keep replays live in the round's kept inputs + const kw = s.keyWidth(); + const k_kept = r.inputs[index][1]; + const vv = k_kept + 4 * total * kw; + const gate = vv + 4 * total * s.valueWidth(); + const beta = gate + 4 * total * s.value_heads; + // the cast, the conv, the split of its output and, for heads of 128, the q and k norms and the gate in one launch + const qn = try o.arena.of(f32, total * kw); + const heads128 = s.key_dim == 128 and kw % 128 == 0; + const kn = if (heads128) k_kept else try o.arena.of(f32, total * kw); + const norm: ?pops.Norm = if (heads128) .{ .q = m.qk.q_weight, .k = m.qk.k_weight, .eps = m.qk.eps } else null; + const gates: pops.Gates = .{ .a = a, .b = b, .a_log = l.a_log, .dt_bias = l.dt_bias, .gate = gate, .beta = beta, .count = total * s.value_heads, .heads = s.value_heads }; + try pops.convSplit(o, qkv, l.conv, qn, kn, vv, r.plan, index, ch, s.conv, kw, s.valueWidth(), norm, if (heads128) gates else null); + var q = qn; + var k = kn; + if (!heads128) { + const qc = try o.arena.of(f32, total * kw); + const kc = k_kept; + try o.rms2(qn, m.qk.q_weight, qc, kn, m.qk.k_weight, kc, total * s.key_heads, s.key_dim, m.qk.eps); + try o.gdnGate(a, b, l.a_log, l.dt_bias, gate, beta, total * s.value_heads, s.value_heads); + q = qc; + k = kc; + } + try pops.gatedDelta(o, q, k, vv, gate, beta, y, r.plan, index, s.key_heads, s.value_heads, s.key_dim, s.value_dim); + return fwd.gatedOut(o, m, l, y, z, total); +} diff --git a/zig/src/families/qwen3_5/backend/hip/model/bridge.zig b/zig/src/families/qwen3_5/backend/hip/model/bridge.zig new file mode 100644 index 00000000000..5b1a5e93164 --- /dev/null +++ b/zig/src/families/qwen3_5/backend/hip/model/bridge.zig @@ -0,0 +1,87 @@ +//! The forward's view of an uploaded model: projections, activation dtype and normalize_qk's constants. + +const std = @import("std"); +const hip = @import("hip"); +const view = @import("view.zig"); +const weights = @import("weights.zig"); + +pub const Error = error{UnsupportedTables} || hip.Error || std.mem.Allocator.Error; + +/// A projection (N, K) from its uploaded tensors, in whichever format they are. +pub fn projection(p: weights.Projection) Error!view.Projection { + return hip.quant.view(p, false); +} + +/// A projection split along K: its fp32 output is one rank's share of the sum. +fn share(p: weights.Projection, sliced: bool) Error!view.Projection { + var a = try projection(p); + a.partial = sliced; + return a; +} + +/// An uploaded MLP as the forward reads it: a dense one's projections, or the routed experts (rank share if `sliced`). +pub fn mlpView(m: weights.Mlp, sliced: bool) Error!view.Mlp { + return switch (m) { + .dense => |d| .{ .dense = .{ .gate = try projection(d.gate), .up = try projection(d.up), .down = try share(d.down, sliced) } }, + .routed => |r| .{ .moe = .{ + .rows32 = r.rows32.ptr, + .top_k = r.top_k, + .rows = r.router.dim(0), + .remap = if (r.remap) |b| b.ptr else 0, + .experts = .{ + .fused = try hip.quant.view(r.experts.fused, true), + .down = try hip.quant.view(r.experts.down, true), + .count = r.experts.count, + .width = r.experts.width, + .dims = r.experts.dims, + }, + } }, + }; +} + +pub const Bridge = struct { + gpa: std.mem.Allocator, + layers: []view.Layer, + q_weight: hip.DeviceBuffer, + k_weight: hip.DeviceBuffer, + model: view.Model, + + /// The view of `m` for activations of `act` (fp16 on RDNA2, bf16 on gfx11 / gfx12). + pub fn init(gpa: std.mem.Allocator, d: *const hip.Runtime, m: *const weights.Model, act: view.Kind) !*Bridge { + const s = m.spec; + const b = try gpa.create(Bridge); + errdefer gpa.destroy(b); + b.gpa = gpa; + b.layers = try gpa.alloc(view.Layer, m.layers.len); + errdefer gpa.free(b.layers); + for (m.layers, b.layers) |l, *out| out.* = switch (l) { + .full => |f| .{ .full = .{ .input_norm = f.input_norm.ptr, .post_norm = f.post_norm.ptr, .q = try projection(f.q), .k = try projection(f.k), .v = try projection(f.v), .o = try share(f.o, m.sliced), .q_norm = f.q_norm.ptr, .k_norm = f.k_norm.ptr, .mlp = try mlpView(f.mlp, m.sliced) } }, + .linear => |x| .{ .linear = .{ .input_norm = x.input_norm.ptr, .post_norm = x.post_norm.ptr, .qkv = try projection(x.qkv), .z = try projection(x.z), .a = try projection(x.a), .b = try projection(x.b), .out = try share(x.out, m.sliced), .conv = x.conv.ptr, .a_log = x.a_log.ptr, .dt_bias = x.dt_bias.ptr, .gnorm = x.gnorm.ptr, .mlp = try mlpView(x.mlp, m.sliced) } }, + }; + const c = view.qkConstants(s.key_dim, s.eps); + const qs = try gpa.alloc(f32, s.key_dim); + defer gpa.free(qs); + @memset(qs, c.q); + b.q_weight = try hip.DeviceBuffer.fromHost(d, std.mem.sliceAsBytes(qs)); + errdefer b.q_weight.free(); + @memset(qs, c.k); + b.k_weight = try hip.DeviceBuffer.fromHost(d, std.mem.sliceAsBytes(qs)); + b.model = .{ + .spec = s, + .act = act, + .embed = try projection(m.embed), + .layers = b.layers, + .final_norm = m.final_norm.ptr, + .head = try projection(m.outputHead()), + .qk = .{ .q_weight = b.q_weight.base(), .k_weight = b.k_weight.base(), .eps = c.eps }, + }; + return b; + } + + pub fn deinit(b: *Bridge) void { + b.q_weight.free(); + b.k_weight.free(); + b.gpa.free(b.layers); + b.gpa.destroy(b); + } +}; diff --git a/zig/src/families/qwen3_5/backend/hip/model/view.zig b/zig/src/families/qwen3_5/backend/hip/model/view.zig new file mode 100644 index 00000000000..4663e038c43 --- /dev/null +++ b/zig/src/families/qwen3_5/backend/hip/model/view.zig @@ -0,0 +1,124 @@ +//! The device weights the forward reads: projections, fp32 norms, conv taps, DeltaNet tables, MLPs and the MTP head. + +const std = @import("std"); +const hip = @import("hip"); + +pub const Projection = hip.quant.Projection; +pub const Kind = hip.ops.Kind; + +/// The text model's dimensions (Python's Spec), as the checkpoint's config gives them. +pub const Spec = @import("../../../weights/config.zig").Spec; + +/// The conv's channels: q, k and v of the linear attention. +pub fn convChannels(s: Spec) usize { + return 2 * s.keyWidth() + s.valueWidth(); +} + +/// A layer's experts, shared expert last: gate and up stacked as one (E + 1, 2 NI, ...) weight, down (E + 1, D, ...). +pub const Experts = struct { + fused: Projection, + down: Projection, + count: usize, + width: usize, + dims: usize, + limit: f32 = 0, +}; + +/// The router's rows in fp32 (E + 1, D), the shared expert's gate last, and the experts. +pub const Routed = struct { + rows32: u64, + experts: Experts, + top_k: usize, + /// The router's rows, E + 1: the model's expert count, whatever share of the experts this rank holds. + rows: usize, + /// A rank's expert ids (int32, E + 1): each id's place among its own, -1 for another rank's; zero on one rank. + remap: u64 = 0, + + /// Routed experts, the shared one not counted. + pub fn count(r: Routed) usize { + return r.rows - 1; + } +}; + +pub const Mlp = union(enum) { + dense: struct { gate: Projection, up: Projection, down: Projection }, + moe: Routed, +}; + +pub const Full = struct { + input_norm: u64, + post_norm: u64, + q: Projection, + k: Projection, + v: Projection, + o: Projection, + q_norm: u64, + k_norm: u64, + mlp: Mlp, +}; + +pub const Linear = struct { + input_norm: u64, + post_norm: u64, + qkv: Projection, + z: Projection, + a: Projection, + b: Projection, + out: Projection, + conv: u64, + a_log: u64, + dt_bias: u64, + gnorm: u64, + mlp: Mlp, +}; + +pub const Layer = union(enum) { full: Full, linear: Linear }; + +/// The MTP head: the Qwen3 shape (gated attention, an MLP or experts) with its own or the model's output head. +pub const Mtp = struct { + fc_e_norm: u64, + fc_h_norm: u64, + fc_e: Projection, + fc_h: Projection, + q_norm: u64, + k_norm: u64, + q: Projection, + k: Projection, + v: Projection, + o: Projection, + final_norm: u64, + head: ?Projection, + input_norm: ?u64, + post_norm: ?u64, + mlp: ?Mlp, + gated: bool, +}; + +/// normalize_qk's constant norm weights (key_dim ** -0.5 squared for q, once for k) and its eps. +pub const QkNorm = struct { q_weight: u64, k_weight: u64, eps: f32 }; + +pub const Model = struct { + /// What this rank sees: under tp its heads and value heads. + spec: Spec, + /// The tensor-parallel communicator; null on one rank. + tp: ?hip.collective.Comm = null, + act: Kind, + embed: Projection, + layers: []const Layer, + final_norm: u64, + head: Projection, + qk: QkNorm, + mtp: ?Mtp = null, +}; + +/// q and k's normalize_qk weights and eps exactly as Python makes them: double arithmetic, then fp32. +pub fn qkConstants(key_dim: usize, eps: f64) struct { q: f32, k: f32, eps: f32 } { + const inv = std.math.pow(f64, @floatFromInt(key_dim), -0.5); + return .{ .q = @floatCast(inv * inv), .k = @floatCast(inv), .eps = @floatCast(eps * inv * inv) }; +} + +test "normalize_qk constants for a 128-wide key" { + const c = qkConstants(128, 1e-6); + try std.testing.expectEqual(@as(f32, 0.0078125), c.q); + try std.testing.expect(@abs(c.k - 0.08838834764) < 1e-8); +} diff --git a/zig/src/families/qwen3_5/backend/hip/model/weights.zig b/zig/src/families/qwen3_5/backend/hip/model/weights.zig new file mode 100644 index 00000000000..1a2c40f8914 --- /dev/null +++ b/zig/src/families/qwen3_5/backend/hip/model/weights.zig @@ -0,0 +1,250 @@ +//! The Qwen3.5 / Qwen3.6 text model on the GPU: the Python TextModel's tensors as device buffers with their dtypes. + +const std = @import("std"); +const hip = @import("hip"); +const config = @import("../../../weights/config.zig"); +const table = @import("../../../weights/table.zig"); +const host = @import("../../../weights/host.zig"); +const checkpoint = @import("../../../weights/checkpoint.zig"); +const slicing = @import("../../../weights/slicing.zig"); + +const quant = hip.quant; +const Tensor = table.Tensor; +pub const DType = table.DType; + +/// One uploaded tensor: its device address and the element type and shape of the bytes there. +pub const Buf = quant.Buf; + +/// A projection on the device in its format: the tensors as that format keeps them. +pub const Projection = quant.Device; + +/// A layer's E + 1 experts, the shared one last; `fused` is gate then up per expert when `gated`. +pub const Experts = struct { + fused: Projection, + gated: bool, + down: Projection, + width: usize, + dims: usize, + count: usize, +}; + +/// Router rows [E + 1, D], the shared gate row last: bf16 as the Python holds them and `rows32` widened. +pub const Routed = struct { router: Buf, rows32: Buf, experts: Experts, top_k: usize, remap: ?Buf = null }; + +pub const DenseMlp = struct { gate: Projection, up: Projection, down: Projection }; + +pub const Mlp = union(enum) { dense: DenseMlp, routed: Routed }; + +pub const LinearLayer = struct { + input_norm: Buf, + post_norm: Buf, + qkv: Projection, + z: Projection, + a: Projection, + b: Projection, + conv: Buf, + a_log: Buf, + dt_bias: Buf, + gnorm: Buf, + out: Projection, + mlp: Mlp, +}; + +pub const FullLayer = struct { + input_norm: Buf, + post_norm: Buf, + q: Projection, + k: Projection, + v: Projection, + o: Projection, + q_norm: Buf, + k_norm: Buf, + mlp: Mlp, +}; + +pub const Layer = union(enum) { linear: LinearLayer, full: FullLayer }; + +pub const MtpHead = struct { + fc_e_norm: Buf, + fc_h_norm: Buf, + fc_e: Projection, + fc_h: Projection, + q_norm: Buf, + k_norm: Buf, + q: Projection, + k: Projection, + v: Projection, + o: Projection, + final_norm: Buf, + /// `null` ties with the main model's output head. + head: ?Projection, + input_norm: ?Buf, + post_norm: ?Buf, + mlp: ?Mlp, + gated: bool, +}; + +/// Device memory of one model; every `Buf` of it is freed by `deinit`. +const Uploader = struct { + up: hip.Upload, + + fn tensor(u: Uploader, t: Tensor) !Buf { + return u.up.uploader().tensor(t); + } + + fn projection(u: Uploader, p: host.Projection) !Projection { + return quant.upload(u.up.uploader(), p); + } + + fn mlp(u: Uploader, m: host.Mlp) !Mlp { + switch (m) { + .dense => |d| return .{ .dense = .{ .gate = try u.projection(d.gate), .up = try u.projection(d.up), .down = try u.projection(d.down) } }, + .routed => |r| { + const e = r.experts; + return .{ .routed = .{ + .router = try u.tensor(r.router), + .rows32 = try u.tensor(r.rows32), + .experts = .{ + .fused = try u.projection(e.fused), + .gated = e.gated, + .down = try u.projection(e.down), + .width = e.width, + .dims = e.dims, + .count = e.count, + }, + .top_k = r.top_k, + .remap = if (r.remap) |t| try u.tensor(t) else null, + } }; + }, + } + } + + fn layer(u: Uploader, l: host.Layer) !Layer { + switch (l.body) { + .linear => |x| return .{ .linear = .{ + .input_norm = try u.tensor(x.input_norm), + .post_norm = try u.tensor(x.post_norm), + .qkv = try u.projection(x.qkv), + .z = try u.projection(x.z), + .a = try u.projection(x.a), + .b = try u.projection(x.b), + .conv = try u.tensor(x.conv), + .a_log = try u.tensor(x.a_log), + .dt_bias = try u.tensor(x.dt_bias), + .gnorm = try u.tensor(x.gnorm), + .out = try u.projection(x.out), + .mlp = try u.mlp(x.mlp), + } }, + .full => |x| return .{ .full = .{ + .input_norm = try u.tensor(x.input_norm), + .post_norm = try u.tensor(x.post_norm), + .q = try u.projection(x.q), + .k = try u.projection(x.k), + .v = try u.projection(x.v), + .o = try u.projection(x.o), + .q_norm = try u.tensor(x.q_norm), + .k_norm = try u.tensor(x.k_norm), + .mlp = try u.mlp(x.mlp), + } }, + } + } + + fn mtp(u: Uploader, m: host.Mtp) !MtpHead { + return .{ + .fc_e_norm = try u.tensor(m.fc_e_norm), + .fc_h_norm = try u.tensor(m.fc_h_norm), + .fc_e = try u.projection(m.fc_e), + .fc_h = try u.projection(m.fc_h), + .q_norm = try u.tensor(m.q_norm), + .k_norm = try u.tensor(m.k_norm), + .q = try u.projection(m.q), + .k = try u.projection(m.k), + .v = try u.projection(m.v), + .o = try u.projection(m.o), + .final_norm = try u.tensor(m.final_norm), + .head = if (m.head) |h| try u.projection(h) else null, + .input_norm = if (m.input_norm) |n| try u.tensor(n) else null, + .post_norm = if (m.post_norm) |n| try u.tensor(n) else null, + .mlp = if (m.mlp) |x| try u.mlp(x) else null, + .gated = m.gated, + }; + } +}; + +pub const Model = struct { + gpa: std.mem.Allocator, + spec: config.Spec, + buffers: std.ArrayList(hip.DeviceBuffer) = .empty, + embed: Projection = undefined, + layers: []Layer = &.{}, + final_norm: Buf = undefined, + /// `null` ties the output head with `embed`. + head: ?Projection = null, + mtp: ?MtpHead = null, + /// A tensor-parallel rank's share: the output projections hold fp32 shares of a sum. + sliced: bool = false, + + /// The text tower of the checkpoint in `dir`, one layer at a time through host memory. + pub fn load(gpa: std.mem.Allocator, io: std.Io, d: *const hip.Runtime, dir: []const u8) !Model { + return loadRank(gpa, io, d, dir, null); + } + + /// As `load`, keeping only tensor-parallel rank `rank`'s share (null: the whole model). + pub fn loadRank(gpa: std.mem.Allocator, io: std.Io, d: *const hip.Runtime, dir: []const u8, rank: ?slicing.Rank) !Model { + var ck = try checkpoint.Checkpoint.open(gpa, io, dir); + defer ck.close(); + return fromCheckpointRank(gpa, d, &ck, std.math.maxInt(usize), rank); + } + + /// The first `limit` layers of `ck` (all when `limit` is large), with the MTP head only when every layer loads. + pub fn fromCheckpoint(gpa: std.mem.Allocator, d: *const hip.Runtime, ck: *const checkpoint.Checkpoint, limit: usize) !Model { + return fromCheckpointRank(gpa, d, ck, limit, null); + } + + /// `fromCheckpoint` for one tensor-parallel rank, `spec` being what that rank sees. + pub fn fromCheckpointRank(gpa: std.mem.Allocator, d: *const hip.Runtime, ck: *const checkpoint.Checkpoint, limit: usize, rank: ?slicing.Rank) !Model { + const whole = ck.spec(); + var m: Model = .{ .gpa = gpa, .spec = if (rank) |r| try slicing.localSpec(whole, r) else whole, .sliced = rank != null }; + errdefer m.deinit(); + const u: Uploader = .{ .up = .{ .r = d, .buffers = &m.buffers, .gpa = gpa } }; + var scratch: std.heap.ArenaAllocator = .init(gpa); + defer scratch.deinit(); + const embed = try ck.embed(scratch.allocator()); + m.embed = try u.projection(embed); + m.final_norm = try u.tensor(try ck.finalNorm(scratch.allocator())); + const head = try ck.head(scratch.allocator()); + if (rank) |r| { + m.head = try u.projection(try slicing.vocabRows(scratch.allocator(), head orelse embed, whole.vocab, r)); + } else if (head) |h| m.head = try u.projection(h); + var list: std.ArrayList(Layer) = .empty; + errdefer list.deinit(gpa); + for (0..@min(limit, m.spec.n_layers)) |i| { + var host_layer = try ck.layer(i); + defer host_layer.deinit(); + if (rank) |r| try slicing.layer(&host_layer, whole, r); + try list.append(gpa, try u.layer(host_layer)); + } + m.layers = try list.toOwnedSlice(gpa); + // under tp only rank 0 drafts: its head is whole, logits rows included (its own or the model's whole head) + const drafts = if (rank) |r| r.rank == 0 else true; + if (drafts and m.layers.len == m.spec.n_layers) if (try ck.mtp()) |head_layer| { + var h = head_layer; + defer h.deinit(); + if (rank != null and h.head == null) h.head = head orelse embed; + m.mtp = try u.mtp(h); + }; + return m; + } + + /// The output head: the embedding itself when the checkpoint ties them. + pub fn outputHead(m: *const Model) Projection { + return m.head orelse m.embed; + } + + pub fn deinit(m: *Model) void { + for (m.buffers.items) |*b| b.free(); + m.buffers.deinit(m.gpa); + m.gpa.free(m.layers); + m.* = undefined; + } +}; diff --git a/zig/src/families/qwen3_5/config.zig b/zig/src/families/qwen3_5/config.zig index 438b0ddd762..7b5cf9e817f 100644 --- a/zig/src/families/qwen3_5/config.zig +++ b/zig/src/families/qwen3_5/config.zig @@ -258,3 +258,287 @@ test "admit untied heads and refuse a root and language tiedness disagreement" { defer gpa.free(mismatch); try std.testing.expectError(error.BadQwenConfig, parse(gpa, mismatch)); } + +// The geometry any backend reads, with its defaults and checks; Metal's admission above is stricter (one geometry). + +pub const Error = error{ + InvalidConfig, + MissingField, + UnsupportedModel, + InvalidMoe, + InvalidRotary, + InvalidLayerTypes, +} || checks.Error || std.mem.Allocator.Error || std.json.ParseError(std.json.Scanner); + +pub const checks = @import("config_checks.zig"); + +/// The Python `Spec`, plus the shared expert's width and the MTP layer count the config declares. +pub const Spec = struct { + hidden: usize, + intermediate: usize, + n_layers: usize, + heads: usize, + kv_heads: usize, + head_dim: usize, + key_heads: usize, + value_heads: usize, + key_dim: usize, + value_dim: usize, + conv: usize, + vocab: usize, + eps: f64, + rope_theta: f64, + rotary_dim: usize, + full_every: usize, + bits: u8, + group: u16, + experts: usize, + top_k: usize, + moe_width: usize, + shared_width: usize, + mtp_layers: usize, + /// Each layer's kind, true for full attention (the others are gated delta-net). + full_layers: [checks.max_layers]bool = @splat(false), + mrope: checks.Mrope = .{}, + max_position: usize = 262144, + + /// Whether layer `index` is full attention (the others are gated delta-net). + pub fn full(s: Spec, index: usize) bool { + return s.full_layers[index]; + } + + pub fn keyWidth(s: Spec) usize { + return s.key_heads * s.key_dim; + } + + pub fn valueWidth(s: Spec) usize { + return s.value_heads * s.value_dim; + } +}; + +/// The config's root object, when its model_type is a Qwen3.5 text model, dense or sparse. +pub fn declared(a: std.mem.Allocator, bytes: []const u8) Error!std.json.ObjectMap { + const doc = try objectOf(try std.json.parseFromSliceLeaky(std.json.Value, a, bytes, .{})); + const kind = doc.get("model_type") orelse return error.UnsupportedModel; + if (kind != .string or !(eql(kind.string, "qwen3_5") or eql(kind.string, "qwen3_5_moe"))) return error.UnsupportedModel; + return doc; +} + +/// The text tower's object: `text_config` when the config has one, else the root itself. +pub fn textTower(doc: std.json.ObjectMap) Error!std.json.ObjectMap { + return if (truthy(doc.get("text_config"))) try objectOf(doc.get("text_config").?) else doc; +} + +/// `cfg.get(key) or text.get(key) or {}`, an object. +pub fn pickObject(doc: std.json.ObjectMap, tower: std.json.ObjectMap, key: []const u8) Error!std.json.ObjectMap { + for ([_]std.json.ObjectMap{ doc, tower }) |source| if (truthy(source.get(key))) return objectOf(source.get(key).?); + return std.json.ObjectMap.empty; +} + +/// `tie_word_embeddings`: the output head is the embedding (the default). +pub fn isTied(doc: std.json.ObjectMap, tower: std.json.ObjectMap) bool { + return if (doc.get("tie_word_embeddings")) |v| truthyValue(v) else if (tower.get("tie_word_embeddings")) |v| truthyValue(v) else true; +} + +/// The Spec of a text tower whose weights are `bits` wide in groups of `group_size`. +pub fn geometry(tower: std.json.ObjectMap, bits: u8, group_size: u16) Error!Spec { + const experts = try optionalInt(tower, "num_experts", 0); + const top_k = try optionalInt(tower, "num_experts_per_tok", 0); + const moe_width = try optionalInt(tower, "moe_intermediate_size", 0); + if (experts != 0) { + if (top_k == 0 or top_k > experts or moe_width == 0) return error.InvalidMoe; + if (tower.get("norm_topk_prob")) |v| if (!truthyValue(v)) return error.InvalidMoe; + } + const model_width = try requiredInt(tower, "hidden_size"); + const attn_heads = try requiredInt(tower, "num_attention_heads"); + const per_head = if (truthy(tower.get("head_dim"))) try toInt(tower.get("head_dim").?) else model_width / attn_heads; + const rope = if (truthy(tower.get("rope_parameters"))) try objectOf(tower.get("rope_parameters").?) else std.json.ObjectMap.empty; + const partial = try numberOf(rope.get("partial_rotary_factor") orelse tower.get("partial_rotary_factor") orelse .{ .float = 0.25 }); + const product = @as(f64, @floatFromInt(per_head)) * partial; + if (!(product >= 0 and product <= @as(f64, @floatFromInt(per_head)))) return error.InvalidRotary; + const rotary: usize = @intFromFloat(product); + const base = try numberOf(rope.get("rope_theta") orelse if (truthy(tower.get("rope_theta"))) tower.get("rope_theta").? else .{ .integer = 10_000_000 }); + var spec: Spec = .{ + .hidden = model_width, + .intermediate = try optionalInt(tower, "intermediate_size", 0), + .n_layers = try requiredInt(tower, "num_hidden_layers"), + .heads = attn_heads, + .kv_heads = try requiredInt(tower, "num_key_value_heads"), + .head_dim = per_head, + .key_heads = try requiredInt(tower, "linear_num_key_heads"), + .value_heads = try requiredInt(tower, "linear_num_value_heads"), + .key_dim = try requiredInt(tower, "linear_key_head_dim"), + .value_dim = try requiredInt(tower, "linear_value_head_dim"), + .conv = try requiredInt(tower, "linear_conv_kernel_dim"), + .vocab = try requiredInt(tower, "vocab_size"), + .eps = try numberOf(tower.get("rms_norm_eps") orelse .{ .float = 1e-6 }), + .rope_theta = base, + .rotary_dim = rotary, + .full_every = try optionalInt(tower, "full_attention_interval", 4), + .bits = bits, + .group = group_size, + .experts = experts, + .top_k = top_k, + .moe_width = moe_width, + .shared_width = try optionalInt(tower, "shared_expert_intermediate_size", 0), + .mtp_layers = try optionalInt(tower, "mtp_num_hidden_layers", 0), + }; + if (rotary % 2 != 0 or rotary == 0 or rotary > per_head) return error.InvalidRotary; + if (spec.full_every == 0 or attn_heads == 0) return error.InvalidConfig; + try checks.computes(tower); + try checks.products(.{ .hidden = spec.hidden, .intermediate = spec.intermediate, .vocab = spec.vocab, .heads = spec.heads, .kv_heads = spec.kv_heads, .head_dim = spec.head_dim, .key_heads = spec.key_heads, .value_heads = spec.value_heads, .key_dim = spec.key_dim, .value_dim = spec.value_dim, .conv = spec.conv, .experts = spec.experts, .moe_width = spec.moe_width, .shared_width = spec.shared_width }); + try checks.layers(&spec.full_layers, tower, spec.n_layers, spec.full_every); + spec.mrope = try checks.mrope(rope, rotary); + spec.max_position = try checks.maxPosition(tower); + return spec; +} + +fn eql(a: []const u8, b: []const u8) bool { + return std.mem.eql(u8, a, b); +} + +fn objectOf(v: std.json.Value) Error!std.json.ObjectMap { + return if (v == .object) v.object else error.InvalidConfig; +} + +/// Python truthiness of an optional JSON value (`x.get(k) or default`). +fn truthy(v: ?std.json.Value) bool { + return if (v) |value| truthyValue(value) else false; +} + +fn truthyValue(v: std.json.Value) bool { + return switch (v) { + .null => false, + .bool => |b| b, + .integer => |i| i != 0, + .float => |f| f != 0, + .string => |s| s.len > 0, + .array => |x| x.items.len > 0, + .object => |o| o.count() > 0, + else => true, + }; +} + +/// Python `int(x)` of a JSON number. +fn toInt(v: std.json.Value) Error!usize { + return switch (v) { + .integer => |i| std.math.cast(usize, i) orelse error.InvalidConfig, + .float => |f| if (f >= 0 and f < 1e15) @intFromFloat(f) else error.InvalidConfig, + else => error.InvalidConfig, + }; +} + +fn numberOf(v: std.json.Value) Error!f64 { + return switch (v) { + .integer => |i| @floatFromInt(i), + .float => |f| f, + else => error.InvalidConfig, + }; +} + +fn requiredInt(o: std.json.ObjectMap, name: []const u8) Error!usize { + return toInt(o.get(name) orelse return error.MissingField); +} + +/// `int(o.get(name, default) or 0)`: absent is `default`, null or zero is 0. +fn optionalInt(o: std.json.ObjectMap, name: []const u8, default: usize) Error!usize { + const v = o.get(name) orelse return default; + return if (truthyValue(v)) toInt(v) else 0; +} + +const sample_text = + \\{"model_type": "qwen3_5", "tie_word_embeddings": false, + \\ "text_config": {"hidden_size": 4096, "intermediate_size": 12288, "num_hidden_layers": 8, + \\ "num_attention_heads": 16, "num_key_value_heads": 4, "head_dim": 256, + \\ "linear_num_key_heads": 16, "linear_num_value_heads": 32, "linear_key_head_dim": 128, + \\ "linear_value_head_dim": 128, "linear_conv_kernel_dim": 4, "vocab_size": 248320, + \\ "rms_norm_eps": 1e-06, "full_attention_interval": 4, "mtp_num_hidden_layers": 1, + \\ "layer_types": ["linear_attention", "linear_attention", "linear_attention", "full_attention", + \\ "linear_attention", "linear_attention", "linear_attention", "full_attention"], + \\ "rope_parameters": {"rope_theta": 10000000, "partial_rotary_factor": 0.25}}} +; + +test "text_config parses into the Python Spec" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const doc = try declared(arena.allocator(), sample_text); + const tower = try textTower(doc); + const s = try geometry(tower, 4, 64); + try std.testing.expectEqual(@as(usize, 4096), s.hidden); + try std.testing.expectEqual(@as(usize, 12288), s.intermediate); + try std.testing.expectEqual(@as(usize, 64), s.rotary_dim); + try std.testing.expectEqual(@as(usize, 256), s.head_dim); + try std.testing.expectEqual(@as(usize, 2048), s.keyWidth()); + try std.testing.expectEqual(@as(usize, 4096), s.valueWidth()); + try std.testing.expectEqual(@as(f64, 10_000_000), s.rope_theta); + try std.testing.expectEqual(@as(f64, 1e-6), s.eps); + try std.testing.expectEqual(@as(u8, 4), s.bits); + try std.testing.expectEqual(@as(u16, 64), s.group); + try std.testing.expectEqual(@as(usize, 0), s.experts); + try std.testing.expectEqual(@as(usize, 1), s.mtp_layers); + try std.testing.expect(!isTied(doc, tower)); + try std.testing.expect(s.full(3) and s.full(7) and !s.full(0) and !s.full(4)); +} + +test "a top-level config, the partial rotary default and the MoE fields" { + const text = + \\{"model_type": "qwen3_5_moe", + \\ "hidden_size": 2048, "num_hidden_layers": 4, "num_attention_heads": 16, "num_key_value_heads": 2, + \\ "linear_num_key_heads": 16, "linear_num_value_heads": 32, "linear_key_head_dim": 128, + \\ "linear_value_head_dim": 128, "linear_conv_kernel_dim": 4, "vocab_size": 1000, "rope_theta": 5000000, + \\ "partial_rotary_factor": 0.5, "num_experts": 256, "num_experts_per_tok": 8, + \\ "moe_intermediate_size": 512, "shared_expert_intermediate_size": 512} + ; + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const doc = try declared(arena.allocator(), text); + const tower = try textTower(doc); + const s = try geometry(tower, 8, 64); + try std.testing.expect(isTied(doc, tower)); + try std.testing.expectEqual(@as(usize, 128), s.head_dim); + try std.testing.expectEqual(@as(usize, 64), s.rotary_dim); + try std.testing.expectEqual(@as(f64, 5_000_000), s.rope_theta); + try std.testing.expectEqual(@as(usize, 256), s.experts); + try std.testing.expectEqual(@as(usize, 8), s.top_k); + try std.testing.expectEqual(@as(usize, 512), s.moe_width); + try std.testing.expectEqual(@as(usize, 512), s.shared_width); + try std.testing.expectEqual(@as(usize, 0), s.intermediate); + try std.testing.expectEqual(@as(usize, 4), s.full_every); +} + +test "the geometry refuses what the kernels do not compute and sizes past 32 bits" { + const a = std.testing.allocator; + var arena: std.heap.ArenaAllocator = .init(a); + defer arena.deinit(); + const cases = [_]struct { []const u8, []const u8, Error }{ + .{ "\"rms_norm_eps\"", "\"hidden_act\": \"gelu\", \"rms_norm_eps\"", error.UnsupportedActivation }, + .{ "\"rms_norm_eps\"", "\"output_gate_type\": \"sigmoid\", \"rms_norm_eps\"", error.UnsupportedAttentionGate }, + .{ "\"rms_norm_eps\"", "\"mamba_ssm_dtype\": \"bfloat16\", \"rms_norm_eps\"", error.UnsupportedStateType }, + .{ "\"vocab_size\": 248320", "\"vocab_size\": 1048576", error.InvalidConfig }, + }; + for (cases) |c| { + const text = try std.mem.replaceOwned(u8, a, sample_text, c[0], c[1]); + defer a.free(text); + try std.testing.expectError(c[2], geometry(try textTower(try declared(arena.allocator(), text)), 4, 64)); + } +} + +test "the Python loader's refusals" { + const a = std.testing.allocator; + var arena: std.heap.ArenaAllocator = .init(a); + defer arena.deinit(); + const wrong = try std.mem.replaceOwned(u8, a, sample_text, "\"qwen3_5\"", "\"llama\""); + defer a.free(wrong); + try std.testing.expectError(error.UnsupportedModel, declared(arena.allocator(), wrong)); + // any mix of the two kinds is read as written; another kind is refused + const mixed = try std.mem.replaceOwned(u8, a, sample_text, "\"full_attention\"],", "\"linear_attention\"],"); + defer a.free(mixed); + const s = try geometry(try textTower(try declared(arena.allocator(), mixed)), 4, 64); + try std.testing.expect(s.full(3) and !s.full(7)); + const types = try std.mem.replaceOwned(u8, a, sample_text, "\"full_attention\"],", "\"sliding_attention\"],"); + defer a.free(types); + try std.testing.expectError(error.InvalidLayerTypes, geometry(try textTower(try declared(arena.allocator(), types)), 4, 64)); + const moe = try std.mem.replaceOwned(u8, a, sample_text, "\"vocab_size\"", "\"num_experts\": 8, \"num_experts_per_tok\": 9, \"vocab_size\""); + defer a.free(moe); + try std.testing.expectError(error.InvalidMoe, geometry(try textTower(try declared(arena.allocator(), moe)), 4, 64)); +} diff --git a/zig/src/families/qwen3_5/config_checks.zig b/zig/src/families/qwen3_5/config_checks.zig new file mode 100644 index 00000000000..fa16b918811 --- /dev/null +++ b/zig/src/families/qwen3_5/config_checks.zig @@ -0,0 +1,221 @@ +//! What a Qwen3.5 config must declare for the HIP engine: activation, gate, state, layers, rope, end ids, sizes. + +const std = @import("std"); + +pub const Error = error{ UnsupportedActivation, UnsupportedAttentionGate, UnsupportedStateType, BadEos, TooManyEos, MissingEos, InvalidConfig, InvalidLayerTypes, InvalidRotary }; + +/// The most end ids a checkpoint may declare across config.json and generation_config.json. +pub const max_eos = 8; + +/// The most decoder layers a config may declare. +pub const max_layers = 128; + +/// Each layer's kind (true: full attention), from `layer_types` in any order, else every `interval`-th layer. +pub fn layers(out: *[max_layers]bool, tower: std.json.ObjectMap, count: usize, interval: usize) Error!void { + if (count == 0 or count > max_layers or interval == 0) return error.InvalidConfig; + out.* = @splat(false); + const list = tower.get("layer_types") orelse .null; + if (list == .null) { + for (out[0..count], 0..) |*full, i| full.* = (i + 1) % interval == 0; + return; + } + if (list != .array or list.array.items.len != count) return error.InvalidLayerTypes; + for (list.array.items, out[0..count]) |item, *full| { + if (isString(item, "full_attention")) full.* = true else if (!isString(item, "linear_attention")) return error.InvalidLayerTypes; + } +} + +/// The multimodal rope's three sections and their interleaving: the text and image positions a vision tower feeds. +pub const Mrope = struct { section: [3]usize = .{ 11, 11, 10 }, interleaved: bool = true }; + +/// `rope_parameters`' mrope fields: three sections filling half the rotary width, interleaved (the kernels' layout). +pub fn mrope(rope: std.json.ObjectMap, rotary: usize) Error!Mrope { + var m: Mrope = .{}; + if (rope.get("mrope_interleaved")) |v| if (!isFlag(v, true)) return error.InvalidRotary; + const list = rope.get("mrope_section") orelse return m; + if (list == .null) return m; + if (list != .array or list.array.items.len != 3) return error.InvalidRotary; + var sum: usize = 0; + for (list.array.items, &m.section) |item, *x| { + if (item != .integer or item.integer < 0) return error.InvalidRotary; + x.* = @intCast(item.integer); + sum += x.*; + } + if (sum * 2 != rotary) return error.InvalidRotary; + return m; +} + +/// `max_position_embeddings`: a positive token count, else the family's 262,144. +pub fn maxPosition(tower: std.json.ObjectMap) Error!usize { + const v = tower.get("max_position_embeddings") orelse return 262144; + if (v != .integer or v.integer <= 0 or v.integer > std.math.maxInt(u32)) return error.InvalidConfig; + return @intCast(v.integer); +} + +/// Refuses a tower whose activation, attention gate, attention bias or recurrent state type the kernels do not compute. +pub fn computes(tower: std.json.ObjectMap) Error!void { + if (tower.get("hidden_act")) |v| if (!isString(v, "silu")) return error.UnsupportedActivation; + // "swish" is the gate the kernels apply, att * sigmoid(gate), as the qwen27 family reads it + if (tower.get("output_gate_type")) |v| if (!isString(v, "swish")) return error.UnsupportedAttentionGate; + if (tower.get("attn_output_gate")) |v| if (!isFlag(v, true)) return error.UnsupportedAttentionGate; + if (tower.get("attention_bias")) |v| if (!isFlag(v, false)) return error.UnsupportedAttentionGate; + inline for (.{ "linear_attn_state_dtype", "mamba_ssm_dtype" }) |key| { + if (tower.get(key)) |v| if (!isString(v, "float32")) return error.UnsupportedStateType; + } +} + +/// The sizes the kernels index with 32-bit counts and the host multiplies: every product must fit. +pub const Sizes = struct { + hidden: usize, + intermediate: usize, + vocab: usize, + heads: usize, + kv_heads: usize, + head_dim: usize, + key_heads: usize, + value_heads: usize, + key_dim: usize, + value_dim: usize, + conv: usize, + experts: usize, + moe_width: usize, + shared_width: usize, +}; + +pub fn products(s: Sizes) Error!void { + if (s.heads % s.kv_heads != 0 or s.value_heads % s.key_heads != 0) return error.InvalidConfig; + const limit: usize = std.math.maxInt(u32); + const q = try mul(try mul(s.heads, s.head_dim), 2); + const kv = try mul(s.kv_heads, s.head_dim); + const k = try mul(s.key_heads, s.key_dim); + const v = try mul(s.value_heads, s.value_dim); + const conv = try mul(try add(try mul(k, 2), v), s.conv); + const state = try mul(try mul(v, s.key_dim), 4); + const widths = [_]usize{ q, kv, conv, state, try mul(s.hidden, s.intermediate), try mul(s.hidden, s.vocab), try mul(s.hidden, try mul(s.experts, s.moe_width)), try mul(s.hidden, s.shared_width) }; + for (widths) |w| if (w > limit) return error.InvalidConfig; +} + +/// The end ids, config.json's (root, then text tower) and generation_config.json's, each once and below `vocab`. +pub fn eos(out: *[max_eos]u32, root: std.json.ObjectMap, tower: std.json.ObjectMap, generation: ?std.json.ObjectMap, vocab: usize) Error![]const u32 { + var n: usize = 0; + const holders = [_]?std.json.Value{ root.get("eos_token_id"), tower.get("eos_token_id"), if (generation) |g| g.get("eos_token_id") else null }; + for (holders) |h| if (h) |v| try collect(out, &n, v, vocab); + if (n == 0) return error.MissingEos; + return out[0..n]; +} + +fn collect(out: *[max_eos]u32, n: *usize, v: std.json.Value, vocab: usize) Error!void { + switch (v) { + .null => {}, + .array => |list| for (list.items) |item| try collect(out, n, item, vocab), + .integer => |i| { + if (i < 0 or i >= vocab) return error.BadEos; + const id: u32 = @intCast(i); + if (std.mem.indexOfScalar(u32, out[0..n.*], id) != null) return; + if (n.* == max_eos) return error.TooManyEos; + out[n.*] = id; + n.* += 1; + }, + else => return error.BadEos, + } +} + +fn mul(a: usize, b: usize) Error!usize { + return std.math.mul(usize, a, b) catch error.InvalidConfig; +} + +fn add(a: usize, b: usize) Error!usize { + return std.math.add(usize, a, b) catch error.InvalidConfig; +} + +fn isString(v: std.json.Value, want: []const u8) bool { + return v == .string and std.mem.eql(u8, v.string, want); +} + +/// A JSON boolean, or the 0 / 1 some conversions write in its place. +fn isFlag(v: std.json.Value, want: bool) bool { + return switch (v) { + .bool => |b| b == want, + .integer => |i| i == @intFromBool(want), + else => false, + }; +} + +fn parsed(a: std.mem.Allocator, text: []const u8) !std.json.ObjectMap { + return (try std.json.parseFromSliceLeaky(std.json.Value, a, text, .{})).object; +} + +test "the computed parts: silu, the swish gate, no bias, fp32 state; 0 and 1 stand for false and true" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + try computes(try parsed(a, "{}")); + try computes(try parsed(a, "{\"hidden_act\":\"silu\",\"output_gate_type\":\"swish\",\"attn_output_gate\":1,\"attention_bias\":0,\"mamba_ssm_dtype\":\"float32\"}")); + try std.testing.expectError(error.UnsupportedActivation, computes(try parsed(a, "{\"hidden_act\":\"gelu\"}"))); + try std.testing.expectError(error.UnsupportedAttentionGate, computes(try parsed(a, "{\"output_gate_type\":\"sigmoid\"}"))); + try std.testing.expectError(error.UnsupportedAttentionGate, computes(try parsed(a, "{\"attn_output_gate\":false}"))); + try std.testing.expectError(error.UnsupportedAttentionGate, computes(try parsed(a, "{\"attention_bias\":true}"))); + try std.testing.expectError(error.UnsupportedStateType, computes(try parsed(a, "{\"mamba_ssm_dtype\":\"bfloat16\"}"))); + try std.testing.expectError(error.UnsupportedStateType, computes(try parsed(a, "{\"linear_attn_state_dtype\":\"float16\"}"))); +} + +test "end ids from config.json and generation_config.json, once each, refused past the vocabulary" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var out: [max_eos]u32 = undefined; + // the 27B: config.json names 248044, generation_config.json adds 248046 + const ids = try eos(&out, try parsed(a, "{}"), try parsed(a, "{\"eos_token_id\":248044}"), try parsed(a, "{\"eos_token_id\":[248046,248044]}"), 248320); + try std.testing.expectEqualSlices(u32, &.{ 248044, 248046 }, ids); + try std.testing.expectError(error.MissingEos, eos(&out, try parsed(a, "{}"), try parsed(a, "{}"), null, 10)); + try std.testing.expectError(error.BadEos, eos(&out, try parsed(a, "{\"eos_token_id\":10}"), try parsed(a, "{}"), null, 10)); + try std.testing.expectError(error.BadEos, eos(&out, try parsed(a, "{\"eos_token_id\":\"2\"}"), try parsed(a, "{}"), null, 10)); + try std.testing.expectError(error.TooManyEos, eos(&out, try parsed(a, "{\"eos_token_id\":[0,1,2,3,4,5,6,7,8]}"), try parsed(a, "{}"), null, 10)); +} + +test "sizes: products past 32 bits and uneven head groups are refused" { + const ok: Sizes = .{ .hidden = 5120, .intermediate = 17408, .vocab = 248320, .heads = 24, .kv_heads = 4, .head_dim = 256, .key_heads = 16, .value_heads = 48, .key_dim = 128, .value_dim = 128, .conv = 4, .experts = 0, .moe_width = 0, .shared_width = 0 }; + try products(ok); + var moe = ok; + moe.experts = 256; + moe.moe_width = 512; + try products(moe); + var wide = ok; + wide.vocab = 1 << 20; + try std.testing.expectError(error.InvalidConfig, products(wide)); + var uneven = ok; + uneven.kv_heads = 5; + try std.testing.expectError(error.InvalidConfig, products(uneven)); + var huge = ok; + huge.hidden = std.math.maxInt(usize) / 2; + try std.testing.expectError(error.InvalidConfig, products(huge)); +} + +test "layer kinds: any order from layer_types, the interval otherwise; wrong length or names refused" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var kinds: [max_layers]bool = undefined; + try layers(&kinds, try parsed(a, "{}"), 8, 4); + try std.testing.expectEqualSlices(bool, &.{ false, false, false, true, false, false, false, true }, kinds[0..8]); + try layers(&kinds, try parsed(a, "{\"layer_types\":[\"full_attention\",\"linear_attention\",\"full_attention\"]}"), 3, 4); + try std.testing.expectEqualSlices(bool, &.{ true, false, true }, kinds[0..3]); + try std.testing.expectError(error.InvalidLayerTypes, layers(&kinds, try parsed(a, "{\"layer_types\":[\"full_attention\"]}"), 3, 4)); + try std.testing.expectError(error.InvalidLayerTypes, layers(&kinds, try parsed(a, "{\"layer_types\":[\"sliding_attention\"]}"), 1, 4)); + try std.testing.expectError(error.InvalidConfig, layers(&kinds, try parsed(a, "{}"), max_layers + 1, 4)); +} + +test "mrope: three sections filling half the rotary width, interleaved; max_position positive" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const m = try mrope(try parsed(a, "{\"mrope_section\":[11,11,10],\"mrope_interleaved\":true}"), 64); + try std.testing.expectEqual([3]usize{ 11, 11, 10 }, m.section); + try std.testing.expectEqual(Mrope{}, try mrope(try parsed(a, "{}"), 64)); + try std.testing.expectError(error.InvalidRotary, mrope(try parsed(a, "{\"mrope_section\":[11,11,11]}"), 64)); + try std.testing.expectError(error.InvalidRotary, mrope(try parsed(a, "{\"mrope_section\":[32,32]}"), 64)); + try std.testing.expectError(error.InvalidRotary, mrope(try parsed(a, "{\"mrope_interleaved\":false}"), 64)); + try std.testing.expectEqual(@as(usize, 262144), try maxPosition(try parsed(a, "{}"))); + try std.testing.expectEqual(@as(usize, 32768), try maxPosition(try parsed(a, "{\"max_position_embeddings\":32768}"))); + try std.testing.expectError(error.InvalidConfig, maxPosition(try parsed(a, "{\"max_position_embeddings\":0}"))); +} diff --git a/zig/src/families/qwen3_5/hip.zig b/zig/src/families/qwen3_5/hip.zig new file mode 100644 index 00000000000..a6a583a4ba4 --- /dev/null +++ b/zig/src/families/qwen3_5/hip.zig @@ -0,0 +1,56 @@ +//! Qwen3.5 / Qwen3.6 text checkpoints for the native HIP engine: configuration, host index and upload. + +pub const config = @import("weights/config.zig"); +pub const table = @import("weights/table.zig"); +pub const host = @import("weights/host.zig"); +pub const checkpoint = @import("weights/checkpoint.zig"); +pub const weights = @import("backend/hip/model/weights.zig"); +pub const Config = config.Config; +pub const Spec = config.Spec; +pub const Checkpoint = checkpoint.Checkpoint; +pub const Model = weights.Model; +pub const view = @import("backend/hip/model/view.zig"); +pub const state = @import("backend/hip/forward/state.zig"); +pub const pages = @import("backend/hip/forward/pages.zig"); +pub const forward = @import("backend/hip/forward/forward.zig"); +pub const window = @import("backend/hip/forward/window.zig"); +pub const plan = @import("backend/hip/forward/plan.zig"); +pub const moe = @import("backend/hip/forward/moe.zig"); +pub const sample = @import("backend/hip/engine/sample.zig"); +pub const draw = @import("backend/hip/engine/draw.zig"); +pub const bridge = @import("backend/hip/model/bridge.zig"); +pub const engine = @import("backend/hip/engine/engine.zig"); +pub const memory = @import("backend/hip/engine/memory.zig"); +pub const prefix = @import("backend/hip/engine/prefix.zig"); +pub const radix = @import("engine_api").prompt_radix; +pub const hip_lanes = @import("backend/hip/engine/hip_lanes.zig"); +pub const mtp = @import("backend/hip/engine/mtp.zig"); +pub const worker = @import("backend/hip/engine/worker.zig"); +pub const slicing = @import("weights/slicing.zig"); +pub const reduce = @import("backend/hip/forward/reduce.zig"); +pub const native_engine = @import("backend/hip/engine/native.zig"); +/// The registry entries of the native server: the dense and the sparse checkpoints. +pub const native = native_engine.Native("qwen3_5"); +pub const native_moe = native_engine.Native("qwen3_5_moe"); + +test { + _ = config; + _ = table; + _ = @import("weights/shard.zig"); + _ = @import("weights/projection.zig"); + _ = @import("weights/checkpoint_test.zig"); + _ = @import("weights/real_test.zig"); + _ = view; + _ = moe; + _ = sample; + _ = prefix; + _ = radix; + _ = native_engine; + _ = pages; + _ = plan; + _ = slicing; + // the engine and its workers compile on a host with no GPU + @import("std").testing.refAllDecls(hip_lanes.Hip); + @import("std").testing.refAllDecls(worker.Worker); + @import("std").testing.refAllDecls(engine.Engine); +} diff --git a/zig/src/families/qwen3_5/loader.zig b/zig/src/families/qwen3_5/loader.zig new file mode 100644 index 00000000000..a6d5f0f0c48 --- /dev/null +++ b/zig/src/families/qwen3_5/loader.zig @@ -0,0 +1,21 @@ +//! Qwen3.5 / Qwen3.6 text checkpoints on the host for the GPU backends: configuration, tensor index, projections, cuts. + +pub const config = @import("weights/config.zig"); +pub const table = @import("weights/table.zig"); +pub const host = @import("weights/host.zig"); +pub const checkpoint = @import("weights/checkpoint.zig"); +pub const slicing = @import("weights/slicing.zig"); +pub const Config = config.Config; +pub const Spec = config.Spec; +pub const Checkpoint = checkpoint.Checkpoint; + +test { + _ = config; + _ = table; + _ = @import("weights/shard.zig"); + _ = @import("weights/projection.zig"); + _ = @import("weights/checkpoint_test.zig"); + _ = @import("weights/real_test.zig"); + @import("std").testing.refAllDecls(slicing); + _ = @import("config.zig"); +} diff --git a/zig/src/families/qwen3_5/weights/checkpoint.zig b/zig/src/families/qwen3_5/weights/checkpoint.zig new file mode 100644 index 00000000000..62300bb1c2f --- /dev/null +++ b/zig/src/families/qwen3_5/weights/checkpoint.zig @@ -0,0 +1,234 @@ +//! A Qwen3.5 / Qwen3.6 checkpoint on the host: the Python ROCm loader's tensor names, fallbacks and conversions. + +const std = @import("std"); +const config = @import("config.zig"); +const table = @import("table.zig"); +const host = @import("host.zig"); +const projection = @import("projection.zig"); +const experts = @import("experts.zig"); + +const Tensor = table.Tensor; +const Table = table.Table; +/// The text tower's key prefix, as the MLX conversions name it. +pub const prefix = "language_model.model."; + +pub const Checkpoint = struct { + gpa: std.mem.Allocator, + io: std.Io, + config: config.Config, + files: table.Files, + main: Table, + + /// Reads config.json and maps the model's own safetensors files. + pub fn open(gpa: std.mem.Allocator, io: std.Io, dir: []const u8) !Checkpoint { + var cfg = try config.Config.read(gpa, io, dir); + errdefer cfg.deinit(); + var files = try table.Files.list(gpa, io, dir); + errdefer files.deinit(); + if (files.model.len == 0) return error.NoSafetensors; + const main = try Table.open(gpa, io, files.model, "", cfg.quant); + return .{ .gpa = gpa, .io = io, .config = cfg, .files = files, .main = main }; + } + + pub fn close(c: *Checkpoint) void { + c.main.close(c.io); + c.files.deinit(); + c.config.deinit(); + c.* = undefined; + } + + pub fn spec(c: *const Checkpoint) config.Spec { + return c.config.spec; + } + + /// The embedding, MLX affine words or a float table the row gather reads; `a` holds any converted tables. + pub fn embed(c: *const Checkpoint, a: std.mem.Allocator) !host.Projection { + const p = try projection.projection(a, &c.main, prefix ++ "embed_tokens"); + if (p.rows() != c.spec().vocab) return error.UnexpectedTensor; + return p; + } + + pub fn finalNorm(c: *const Checkpoint, a: std.mem.Allocator) !Tensor { + return projection.float(a, &c.main, prefix ++ "norm.weight"); + } + + /// The output head, or null when it is the embedding (`tie_word_embeddings`). + pub fn head(c: *const Checkpoint, a: std.mem.Allocator) !?host.Projection { + if (c.config.tied) return null; + return try projection.projection(a, &c.main, "language_model.lm_head"); + } + + /// Layer `index`, read and converted; free it with `deinit`. + pub fn layer(c: *const Checkpoint, index: usize) !host.Layer { + const s = c.spec(); + if (index >= s.n_layers) return error.InvalidModel; + var arena: std.heap.ArenaAllocator = .init(c.gpa); + errdefer arena.deinit(); + const a = arena.allocator(); + const t = &c.main; + var name: [128]u8 = undefined; + const base = std.fmt.bufPrint(&name, prefix ++ "layers.{d}.", .{index}) catch unreachable; + var scratch: [160]u8 = undefined; + const input_norm = try projection.float(a, t, projection.join(&scratch, &.{ base, "input_layernorm.weight" })); + const post_norm = try projection.float(a, t, projection.join(&scratch, &.{ base, "post_attention_layernorm.weight" })); + const mlp = try readMlp(a, t, projection.join(&scratch, &.{ base, "mlp." }), s); + if (s.full(index)) { + const attn = projection.join(&scratch, &.{ base, "self_attn." }); + const body: host.Body = .{ .full = .{ + .input_norm = input_norm, + .post_norm = post_norm, + .q = try sub(a, t, attn, "q_proj"), + .k = try sub(a, t, attn, "k_proj"), + .v = try sub(a, t, attn, "v_proj"), + .o = try sub(a, t, attn, "o_proj"), + .q_norm = try subFloat(a, t, attn, "q_norm.weight"), + .k_norm = try subFloat(a, t, attn, "k_norm.weight"), + .mlp = mlp, + } }; + return .{ .arena = arena, .body = body }; + } + const lin = projection.join(&scratch, &.{ base, "linear_attn." }); + // the arena is copied into the result last: allocations made after the copy would be lost + const body: host.Body = .{ .linear = .{ + .input_norm = input_norm, + .post_norm = post_norm, + .qkv = try sub(a, t, lin, "in_proj_qkv"), + .z = try sub(a, t, lin, "in_proj_z"), + .a = try sub(a, t, lin, "in_proj_a"), + .b = try sub(a, t, lin, "in_proj_b"), + .conv = try subConv(a, t, lin), + .a_log = try subFloat(a, t, lin, "A_log"), + .dt_bias = try subFloat(a, t, lin, "dt_bias"), + .gnorm = try subFloat(a, t, lin, "norm.weight"), + .out = try sub(a, t, lin, "out_proj"), + .mlp = mlp, + } }; + return .{ .arena = arena, .body = body }; + } + + /// The MTP layer from `mtp*.safetensors` or the model's own shards; null when absent. + pub fn mtp(c: *const Checkpoint) !?host.Mtp { + const side = c.files.side; + const shards = if (side.len > 0) side else c.files.model; + if (shards.len == 0) return null; + const own = c.main.has("mtp.norm_e.weight") or c.main.has("mtp.pre_fc_norm_embedding.weight"); + var opened: ?Table = null; + errdefer if (opened) |*o| o.close(c.io); + var t = &c.main; + if (side.len > 0 or !own) { + opened = try Table.open(c.gpa, c.io, shards, "language_model.", c.config.quant); + t = &opened.?; + } + if (side.len == 0 and !t.has("mtp.norm_e.weight") and !t.has("mtp.pre_fc_norm_embedding.weight")) { + if (opened) |*o| o.close(c.io); + return null; + } + var arena: std.heap.ArenaAllocator = .init(c.gpa); + errdefer arena.deinit(); + var m = try readMtp(arena.allocator(), t, c.spec()); + m.arena = arena; + m.owned = opened; + m.io = c.io; + return m; + } +}; + +fn sub(a: std.mem.Allocator, t: *const Table, base: []const u8, name: []const u8) !host.Projection { + var buf: [192]u8 = undefined; + return projection.projection(a, t, projection.join(&buf, &.{ base, name })); +} + +fn subFloat(a: std.mem.Allocator, t: *const Table, base: []const u8, name: []const u8) !Tensor { + var buf: [192]u8 = undefined; + return projection.float(a, t, projection.join(&buf, &.{ base, name })); +} + +fn subConv(a: std.mem.Allocator, t: *const Table, base: []const u8) !Tensor { + var buf: [192]u8 = undefined; + return projection.conv(a, t, projection.join(&buf, &.{ base, "conv1d.weight" })); +} + +/// The routed MLP when the config has experts, else gate, up and down. +fn readMlp(a: std.mem.Allocator, t: *const Table, mlp: []const u8, s: config.Spec) !host.Mlp { + if (s.experts != 0) return .{ .routed = try experts.routed(a, t, mlp, s) }; + return .{ .dense = .{ + .gate = try sub(a, t, mlp, "gate_proj"), + .up = try sub(a, t, mlp, "up_proj"), + .down = try sub(a, t, mlp, "down_proj"), + } }; +} + +/// The head's tensors under `mtp.`: the Qwen3 shape (`pre_fc_norm_embedding`) or the Flash Next one (`norm_e`). +fn readMtp(a: std.mem.Allocator, t: *const Table, s: config.Spec) !host.Mtp { + const head: ?host.Projection = if (t.has("mtp.head_proj.weight")) try projection.projection(a, t, "mtp.head_proj") else null; + if (!t.has("mtp.pre_fc_norm_embedding.weight")) { + return .{ + .arena = undefined, + .io = undefined, + .fc_e_norm = try projection.float(a, t, "mtp.norm_e.weight"), + .fc_h_norm = try projection.float(a, t, "mtp.norm_h.weight"), + .fc_e = try projection.projection(a, t, "mtp.fc_e"), + .fc_h = try projection.projection(a, t, "mtp.fc_h"), + .q_norm = try projection.float(a, t, "mtp.q_norm.weight"), + .k_norm = try projection.float(a, t, "mtp.k_norm.weight"), + .q = try projection.projection(a, t, "mtp.q_proj"), + .k = try projection.projection(a, t, "mtp.k_proj"), + .v = try projection.projection(a, t, "mtp.v_proj"), + .o = try projection.projection(a, t, "mtp.o_proj"), + .final_norm = try projection.float(a, t, "mtp.final_norm.weight"), + .head = head, + .input_norm = null, + .post_norm = null, + .mlp = null, + .gated = false, + }; + } + const layer = "mtp.layers.0."; + const attn = layer ++ "self_attn."; + const mlp = layer ++ "mlp."; + const halves = try projection.halves(a, try projection.projection(a, t, "mtp.fc")); + const routed = t.has(mlp ++ "switch_mlp.up_proj.weight") or t.has(mlp ++ "switch_mlp.up_proj.qweight"); + var m: host.Mtp = .{ + .arena = undefined, + .io = undefined, + .fc_e_norm = try projection.float(a, t, "mtp.pre_fc_norm_embedding.weight"), + .fc_h_norm = try projection.float(a, t, "mtp.pre_fc_norm_hidden.weight"), + .fc_e = halves[0], + .fc_h = halves[1], + .q_norm = try projection.float(a, t, attn ++ "q_norm.weight"), + .k_norm = try projection.float(a, t, attn ++ "k_norm.weight"), + .q = try projection.projection(a, t, attn ++ "q_proj"), + .k = try projection.projection(a, t, attn ++ "k_proj"), + .v = try projection.projection(a, t, attn ++ "v_proj"), + .o = try projection.projection(a, t, attn ++ "o_proj"), + .final_norm = try projection.float(a, t, "mtp.norm.weight"), + .head = head, + .input_norm = try projection.float(a, t, layer ++ "input_layernorm.weight"), + .post_norm = try projection.float(a, t, layer ++ "post_attention_layernorm.weight"), + .mlp = if (routed) .{ .routed = try experts.routed(a, t, mlp, s) } else .{ .dense = .{ + .gate = try projection.projection(a, t, mlp ++ "gate_proj"), + .up = try projection.projection(a, t, mlp ++ "up_proj"), + .down = try projection.projection(a, t, mlp ++ "down_proj"), + } }, + .gated = true, + }; + try uncenter(a, &m); + return m; +} + +/// Norms averaging under 0.5 are zero-centered (mlx-serve bakes only the trunk's `1 + w`): add the 1. +fn uncenter(a: std.mem.Allocator, m: *host.Mtp) !void { + const norms = [_]*Tensor{ &m.fc_e_norm, &m.fc_h_norm, &m.q_norm, &m.k_norm, &m.final_norm, &m.input_norm.?, &m.post_norm.? }; + var sum: f64 = 0; + var n: usize = 0; + for (norms) |t| for (std.mem.bytesAsSlice(f32, t.bytes)) |w| { + sum += w; + n += 1; + }; + if (sum >= 0.5 * @as(f64, @floatFromInt(n))) return; + for (norms) |t| { + const out = try a.alloc(f32, t.numel()); + for (out, std.mem.bytesAsSlice(f32, t.bytes)) |*o, w| o.* = w + 1; + t.bytes = std.mem.sliceAsBytes(out); + } +} diff --git a/zig/src/families/qwen3_5/weights/checkpoint_test.zig b/zig/src/families/qwen3_5/weights/checkpoint_test.zig new file mode 100644 index 00000000000..02bc4f44833 --- /dev/null +++ b/zig/src/families/qwen3_5/weights/checkpoint_test.zig @@ -0,0 +1,316 @@ +//! Host tests of the checkpoint index on small synthetic safetensors files, checked against the Python loader's rules. + +const std = @import("std"); +const checkpoint = @import("checkpoint.zig"); +const convert = @import("core").quant.convert; +const host = @import("host.zig"); +const DType = @import("table.zig").DType; + +const io = std.testing.io; +const gpa = std.testing.allocator; + +/// One tensor of a synthetic file: `bytes` (or `size` bytes of a name-seeded pattern). +const Entry = struct { name: []const u8, dtype: []const u8, shape: []const usize, bytes: []const u8 = &.{} }; + +const Image = struct { + arena: std.heap.ArenaAllocator, + entries: std.ArrayList(Entry) = .empty, + /// When set, every bf16 tensor named for a norm holds this value's bits instead of the pattern. + norm: ?u16 = null, + + fn init() Image { + return .{ .arena = .init(gpa) }; + } + + fn deinit(m: *Image) void { + m.arena.deinit(); + } + + fn elems(shape: []const usize) usize { + var n: usize = 1; + for (shape) |d| n *= d; + return n; + } + + /// A tensor whose bytes are a pattern seeded by its name (`bits` per element for the size). + fn put(m: *Image, name: []const u8, dtype: []const u8, shape: []const usize) !void { + const a = m.arena.allocator(); + const size: usize = if (std.mem.eql(u8, dtype, "BF16")) 2 else 4; + const bytes = try a.alloc(u8, elems(shape) * size); + var seed: u8 = 0; + for (name) |c| seed +%= c; + for (bytes, 0..) |*b, i| b.* = seed +% @as(u8, @truncate(i * 7)); + // bf16 patterns stay finite: a high byte under 0x40 is a small positive number + if (size == 2) for (bytes[1..], 0..) |*b, i| { + if (i % 2 == 0) b.* &= 0x3F; + }; + if (m.norm) |v| if (size == 2 and std.mem.indexOf(u8, name, "norm") != null) { + for (std.mem.bytesAsSlice(u16, bytes)) |*w| w.* = std.mem.nativeToLittle(u16, v); + }; + try m.entries.append(a, .{ .name = try a.dupe(u8, name), .dtype = dtype, .shape = try a.dupe(usize, shape), .bytes = bytes }); + } + + /// An affine projection [n, k] at `bits`: words, scales and biases. + fn affine(m: *Image, name: []const u8, n: usize, k: usize, bits: usize, group: usize) !void { + var buf: [160]u8 = undefined; + try m.put(try std.fmt.bufPrint(&buf, "{s}.weight", .{name}), "U32", &.{ n, k * bits / 32 }); + try m.put(try std.fmt.bufPrint(&buf, "{s}.scales", .{name}), "BF16", &.{ n, k / group }); + try m.put(try std.fmt.bufPrint(&buf, "{s}.biases", .{name}), "BF16", &.{ n, k / group }); + } + + fn find(m: *const Image, name: []const u8) []const u8 { + for (m.entries.items) |e| if (std.mem.eql(u8, e.name, name)) return e.bytes; + unreachable; + } + + fn write(m: *Image, dir: std.Io.Dir, file: []const u8) !void { + const a = m.arena.allocator(); + var header: std.ArrayList(u8) = .empty; + var data: std.ArrayList(u8) = .empty; + try header.append(a, '{'); + for (m.entries.items, 0..) |e, i| { + const start = data.items.len; + try data.appendSlice(a, e.bytes); + try header.print(a, "{s}\"{s}\":{{\"dtype\":\"{s}\",\"shape\":[", .{ if (i > 0) "," else "", e.name, e.dtype }); + for (e.shape, 0..) |d, j| try header.print(a, "{s}{d}", .{ if (j > 0) "," else "", d }); + try header.print(a, "],\"data_offsets\":[{d},{d}]}}", .{ start, data.items.len }); + } + try header.append(a, '}'); + var out: std.ArrayList(u8) = .empty; + try out.appendSlice(a, &std.mem.toBytes(std.mem.nativeToLittle(u64, header.items.len))); + try out.appendSlice(a, header.items); + try out.appendSlice(a, data.items); + try dir.writeFile(io, .{ .sub_path = file, .data = out.items }); + } +}; + +const dense_config = + \\{"model_type": "qwen3_5", "tie_word_embeddings": true, + \\ "quantization": {"group_size": 32, "bits": 4, "mode": "affine"}, + \\ "text_config": {"hidden_size": 64, "intermediate_size": 32, "num_hidden_layers": 2, + \\ "num_attention_heads": 2, "num_key_value_heads": 1, "head_dim": 32, "linear_num_key_heads": 1, + \\ "linear_num_value_heads": 2, "linear_key_head_dim": 32, "linear_value_head_dim": 16, + \\ "linear_conv_kernel_dim": 4, "vocab_size": 16, "full_attention_interval": 2, + \\ "layer_types": ["linear_attention", "full_attention"], "eos_token_id": 1}} +; + +const moe_config = + \\{"model_type": "qwen3_5_moe", "tie_word_embeddings": true, + \\ "quantization": {"group_size": 32, "bits": 4, "mode": "affine", + \\ "language_model.model.layers.0.mlp.gate": {"group_size": 32, "bits": 8}, + \\ "language_model.model.layers.0.mlp.shared_expert_gate": {"group_size": 32, "bits": 8}}, + \\ "text_config": {"hidden_size": 64, "num_hidden_layers": 1, "num_attention_heads": 2, + \\ "num_key_value_heads": 1, "head_dim": 32, "linear_num_key_heads": 1, "linear_num_value_heads": 2, + \\ "linear_key_head_dim": 32, "linear_value_head_dim": 16, "linear_conv_kernel_dim": 4, "vocab_size": 16, + \\ "full_attention_interval": 1, "num_experts": 2, "num_experts_per_tok": 1, "moe_intermediate_size": 32, + \\ "shared_expert_intermediate_size": 32, "eos_token_id": 1}} +; + +const L = "language_model.model."; + +fn attention(m: *Image, base: []const u8) !void { + var buf: [160]u8 = undefined; + const shapes = [_]struct { []const u8, usize }{ .{ "q_proj", 64 }, .{ "k_proj", 32 }, .{ "v_proj", 32 }, .{ "o_proj", 64 } }; + for (shapes) |p| try m.affine(try std.fmt.bufPrint(&buf, "{s}self_attn.{s}", .{ base, p[0] }), p[1], 64, 4, 32); + try m.put(try std.fmt.bufPrint(&buf, "{s}self_attn.q_norm.weight", .{base}), "BF16", &.{32}); + try m.put(try std.fmt.bufPrint(&buf, "{s}self_attn.k_norm.weight", .{base}), "BF16", &.{32}); +} + +fn norms(m: *Image, base: []const u8) !void { + var buf: [160]u8 = undefined; + try m.put(try std.fmt.bufPrint(&buf, "{s}input_layernorm.weight", .{base}), "BF16", &.{64}); + try m.put(try std.fmt.bufPrint(&buf, "{s}post_attention_layernorm.weight", .{base}), "BF16", &.{64}); +} + +fn trunk(m: *Image) !void { + try m.affine(L ++ "embed_tokens", 16, 64, 4, 32); + try m.put(L ++ "norm.weight", "BF16", &.{64}); +} + +/// The dense test model: a linear layer, a full one, the vision tower to skip and the MTP head in a side file. +fn denseFiles(img: *Image, side: *Image, dir: std.Io.Dir) !void { + try trunk(img); + try norms(img, L ++ "layers.0."); + const lin = L ++ "layers.0.linear_attn."; + try img.affine(lin ++ "in_proj_qkv", 96, 64, 4, 32); + try img.affine(lin ++ "in_proj_z", 32, 64, 4, 32); + try img.affine(lin ++ "in_proj_a", 2, 64, 4, 32); + try img.affine(lin ++ "in_proj_b", 2, 64, 4, 32); + try img.put(lin ++ "conv1d.weight", "BF16", &.{ 96, 4, 1 }); + try img.put(lin ++ "A_log", "BF16", &.{2}); + try img.put(lin ++ "dt_bias", "BF16", &.{2}); + try img.put(lin ++ "norm.weight", "BF16", &.{16}); + try img.affine(lin ++ "out_proj", 64, 32, 4, 32); + inline for (.{ "layers.0.", "layers.1." }) |l| { + try img.affine(L ++ l ++ "mlp.gate_proj", 32, 64, 4, 32); + try img.affine(L ++ l ++ "mlp.up_proj", 32, 64, 4, 32); + try img.affine(L ++ l ++ "mlp.down_proj", 64, 32, 4, 32); + } + try norms(img, L ++ "layers.1."); + try attention(img, L ++ "layers.1."); + try img.put("vision_tower.patch_embed.weight", "BF16", &.{4}); + + try side.put("mtp.pre_fc_norm_embedding.weight", "BF16", &.{64}); + try side.put("mtp.pre_fc_norm_hidden.weight", "BF16", &.{64}); + try side.put("mtp.norm.weight", "BF16", &.{64}); + try side.affine("mtp.fc", 64, 128, 4, 32); + try norms(side, "mtp.layers.0."); + try attention(side, "mtp.layers.0."); + try side.affine("mtp.layers.0.mlp.gate_proj", 32, 64, 4, 32); + try side.affine("mtp.layers.0.mlp.up_proj", 32, 64, 4, 32); + try side.affine("mtp.layers.0.mlp.down_proj", 64, 32, 4, 32); + + try img.write(dir, "model.safetensors"); + try side.write(dir, "mtp.safetensors"); + try dir.writeFile(io, .{ .sub_path = "config.json", .data = dense_config }); +} + +test "a dense model: layers, embedding, tied head and the MTP side file" { + var img = Image.init(); + defer img.deinit(); + var side = Image.init(); + defer side.deinit(); + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + try denseFiles(&img, &side, tmp.dir); + const root = try std.fmt.allocPrint(gpa, ".zig-cache/tmp/{s}", .{tmp.sub_path}); + defer gpa.free(root); + + var ck = try checkpoint.Checkpoint.open(gpa, io, root); + defer ck.close(); + var scratch: std.heap.ArenaAllocator = .init(gpa); + defer scratch.deinit(); + const embed = try ck.embed(scratch.allocator()); + try std.testing.expectEqual(@as(u8, 4), embed.mlx.bits); + try std.testing.expectEqual(host.Tensor{ .dtype = .i32, .rank = 2, .shape = .{ 16, 8, 1, 1, 1 }, .bytes = embed.mlx.words.bytes }, embed.mlx.words); + try std.testing.expect(try ck.head(scratch.allocator()) == null); + const final = try ck.finalNorm(scratch.allocator()); + try std.testing.expectEqual(convert.load(.bf16, img.find(L ++ "norm.weight"), 5), convert.load(.f32, final.bytes, 5)); + + const lin = L ++ "layers.0.linear_attn."; + var l0 = try ck.layer(0); + defer l0.deinit(); + const x = l0.body.linear; + // the conv weight loses its trailing 1 and is widened to fp32 + try std.testing.expectEqual(@as(u8, 2), x.conv.rank); + try std.testing.expectEqual(DType.f32, x.conv.dtype); + try std.testing.expectEqual(@as(usize, 4), x.conv.shape[1]); + try std.testing.expectEqual(convert.load(.bf16, img.find(lin ++ "conv1d.weight"), 9), convert.load(.f32, x.conv.bytes, 9)); + try std.testing.expectEqual(@as(usize, 96), x.qkv.mlx.words.shape[0]); + try std.testing.expectEqualSlices(u8, img.find(lin ++ "in_proj_qkv.weight"), x.qkv.mlx.words.bytes); + try std.testing.expectEqual(DType.bf16, x.qkv.mlx.scales.dtype); + try std.testing.expectEqual(@as(usize, 16), x.gnorm.numel()); + try std.testing.expect(x.mlp == .dense); + + var l1 = try ck.layer(1); + defer l1.deinit(); + try std.testing.expectEqual(@as(usize, 64), l1.body.full.q.rows()); + try std.testing.expectError(error.InvalidModel, ck.layer(2)); + + var head = (try ck.mtp()).?; + defer head.deinit(); + try std.testing.expect(head.gated and head.head == null and head.mlp.? == .dense); + // fc [64, 128] splits into two [64, 64] halves, row by row, words and tables on the same boundary + const words = side.find("mtp.fc.weight"); + const scales = side.find("mtp.fc.scales"); + for ([_]usize{ 0, 63 }) |r| { + try std.testing.expectEqualSlices(u8, words[r * 64 ..][0..32], head.fc_e.mlx.words.bytes[r * 32 ..][0..32]); + try std.testing.expectEqualSlices(u8, words[r * 64 + 32 ..][0..32], head.fc_h.mlx.words.bytes[r * 32 ..][0..32]); + try std.testing.expectEqualSlices(u8, scales[r * 8 + 4 ..][0..4], head.fc_h.mlx.scales.bytes[r * 4 ..][0..4]); + } +} + +test "MoE experts: gate and up fused per expert, the shared expert last, router rows with the shared gate last" { + var img = Image.init(); + defer img.deinit(); + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + const base = L ++ "layers.0."; + const mlp = base ++ "mlp."; + try trunk(&img); + try norms(&img, base); + try attention(&img, base); + try img.affine(mlp ++ "gate", 2, 64, 8, 32); + try img.affine(mlp ++ "shared_expert_gate", 1, 64, 8, 32); + for ([_][]const u8{ "gate_proj", "up_proj" }) |p| { + var buf: [160]u8 = undefined; + for ([_][]const u8{ "weight", "scales", "biases" }) |part| { + const small = std.mem.eql(u8, part, "weight"); + try img.put(try std.fmt.bufPrint(&buf, "{s}switch_mlp.{s}.{s}", .{ mlp, p, part }), if (small) "U32" else "BF16", if (small) &.{ 2, 32, 8 } else &.{ 2, 32, 2 }); + try img.put(try std.fmt.bufPrint(&buf, "{s}shared_expert.{s}.{s}", .{ mlp, p, part }), if (small) "U32" else "BF16", if (small) &.{ 32, 8 } else &.{ 32, 2 }); + } + } + for ([_][]const u8{ "weight", "scales", "biases" }) |part| { + var buf: [160]u8 = undefined; + const small = std.mem.eql(u8, part, "weight"); + try img.put(try std.fmt.bufPrint(&buf, "{s}switch_mlp.down_proj.{s}", .{ mlp, part }), if (small) "U32" else "BF16", if (small) &.{ 2, 64, 4 } else &.{ 2, 64, 1 }); + // the shared expert may carry a leading 1 + try img.put(try std.fmt.bufPrint(&buf, "{s}shared_expert.down_proj.{s}", .{ mlp, part }), if (small) "U32" else "BF16", if (small) &.{ 1, 64, 4 } else &.{ 1, 64, 1 }); + } + try img.write(tmp.dir, "model.safetensors"); + try tmp.dir.writeFile(io, .{ .sub_path = "config.json", .data = moe_config }); + const root = try std.fmt.allocPrint(gpa, ".zig-cache/tmp/{s}", .{tmp.sub_path}); + defer gpa.free(root); + + var ck = try checkpoint.Checkpoint.open(gpa, io, root); + defer ck.close(); + try std.testing.expect(try ck.mtp() == null); + var layer = try ck.layer(0); + defer layer.deinit(); + const r = layer.body.full.mlp.routed; + const e = r.experts; + try std.testing.expect(e.gated and e.count == 3 and e.width == 32 and e.dims == 64); + try std.testing.expectEqual(@as(usize, 3), e.fused.mlx.words.shape[0]); + try std.testing.expectEqual(@as(usize, 64), e.fused.mlx.words.shape[1]); + const per = 32 * 8 * 4; + const gate = img.find(mlp ++ "switch_mlp.gate_proj.weight"); + const up = img.find(mlp ++ "switch_mlp.up_proj.weight"); + const fused = e.fused.mlx.words.bytes; + try std.testing.expectEqualSlices(u8, gate[per .. 2 * per], fused[(2 * per) * 1 ..][0..per]); + try std.testing.expectEqualSlices(u8, up[per .. 2 * per], fused[(2 * per) * 1 + per ..][0..per]); + try std.testing.expectEqualSlices(u8, img.find(mlp ++ "shared_expert.gate_proj.weight"), fused[2 * 2 * per ..][0..per]); + try std.testing.expectEqualSlices(u8, img.find(mlp ++ "shared_expert.up_proj.weight"), fused[2 * 2 * per + per ..][0..per]); + try std.testing.expectEqualSlices(u8, img.find(mlp ++ "shared_expert.down_proj.scales"), e.down.mlx.scales.bytes[2 * 64 * 2 ..][0 .. 64 * 2]); + // the router: 8-bit codes unpacked as s * q + b, rounded to bf16, the shared gate row last + try std.testing.expectEqualSlices(usize, &.{ 3, 64 }, r.router.shape[0..2]); + const words = img.find(mlp ++ "gate.weight"); + const scales = img.find(mlp ++ "gate.scales"); + const biases = img.find(mlp ++ "gate.biases"); + for ([_]usize{ 0, 7, 70, 127 }) |i| { + const row = i / 64; + const code: f32 = @floatFromInt(words[i]); + const g = row * 2 + (i % 64) / 32; + const want = convert.bf16(code * convert.load(.bf16, scales, g) + convert.load(.bf16, biases, g)); + try std.testing.expectEqual(want, std.mem.readInt(u16, r.router.bytes[2 * i ..][0..2], .little)); + try std.testing.expectEqual(@as(u32, want) << 16, std.mem.readInt(u32, r.rows32.bytes[4 * i ..][0..4], .little)); + } + const shared_words = img.find(mlp ++ "shared_expert_gate.weight"); + const last: f32 = @floatFromInt(shared_words[5]); + const sg = 0; + try std.testing.expectEqual( + convert.bf16(last * convert.load(.bf16, img.find(mlp ++ "shared_expert_gate.scales"), sg) + convert.load(.bf16, img.find(mlp ++ "shared_expert_gate.biases"), sg)), + std.mem.readInt(u16, r.router.bytes[2 * (128 + 5) ..][0..2], .little), + ); +} + +test "an MTP head shipped zero-centered gets back the 1 the trunk has baked in; a baked head keeps its gains" { + // bf16 0.25 (mlx-serve's zero-centered head) reads as 1.25; bf16 1.25 (baked) stays 1.25 + for ([_]u16{ 0x3E80, 0x3FA0 }) |bits| { + var img = Image.init(); + defer img.deinit(); + var side = Image.init(); + defer side.deinit(); + side.norm = bits; + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + try denseFiles(&img, &side, tmp.dir); + const root = try std.fmt.allocPrint(gpa, ".zig-cache/tmp/{s}", .{tmp.sub_path}); + defer gpa.free(root); + var ck = try checkpoint.Checkpoint.open(gpa, io, root); + defer ck.close(); + var head = (try ck.mtp()).?; + defer head.deinit(); + for ([_]host.Tensor{ head.fc_e_norm, head.fc_h_norm, head.q_norm, head.k_norm, head.final_norm, head.input_norm.?, head.post_norm.? }) |t| + try std.testing.expectEqual(@as(f64, 1.25), convert.load(.f32, t.bytes, 3)); + } +} diff --git a/zig/src/families/qwen3_5/weights/config.zig b/zig/src/families/qwen3_5/weights/config.zig new file mode 100644 index 00000000000..1161e6eb6c7 --- /dev/null +++ b/zig/src/families/qwen3_5/weights/config.zig @@ -0,0 +1,102 @@ +//! The HIP loader's configuration: the family's geometry (../config.zig) with the checkpoint's quantization table. + +const std = @import("std"); +const quant = @import("core").quant; +const shared = @import("../config.zig"); + +pub const Error = shared.Error || error{UnsupportedQuantization}; + +/// One affine width: MLX groups of `group` weights share a scale and a bias, `bits` per weight. +pub const Width = quant.mlx.Width; + +pub const Spec = shared.Spec; + +pub const Config = struct { + arena: std.heap.ArenaAllocator, + spec: Spec, + quant: quant.Config, + /// `tie_word_embeddings`: the output head is the embedding. + tied: bool, + /// The end ids of config.json and generation_config.json. + eos: []const u32, + + pub fn deinit(c: *Config) void { + c.arena.deinit(); + c.* = undefined; + } + + /// The config of the checkpoint directory `dir`. + pub fn read(gpa: std.mem.Allocator, io: std.Io, dir: []const u8) !Config { + const path = try std.fs.path.join(gpa, &.{ dir, "config.json" }); + defer gpa.free(path); + const bytes = try std.Io.Dir.cwd().readFileAlloc(io, path, gpa, .limited(1 << 26)); + defer gpa.free(bytes); + const gen_path = try std.fs.path.join(gpa, &.{ dir, "generation_config.json" }); + defer gpa.free(gen_path); + const generation = std.Io.Dir.cwd().readFileAlloc(io, gen_path, gpa, .limited(1 << 20)) catch |e| switch (e) { + error.FileNotFound => null, + else => return e, + }; + defer if (generation) |g| gpa.free(g); + return parse(gpa, bytes, generation); + } + + /// `load()`'s reading of config.json (root or `text_config`, qwen3_5 or qwen3_5_moe) and generation_config.json. + pub fn parse(gpa: std.mem.Allocator, bytes: []const u8, generation: ?[]const u8) Error!Config { + var arena: std.heap.ArenaAllocator = .init(gpa); + errdefer arena.deinit(); + const a = arena.allocator(); + const doc = try shared.declared(a, bytes); + const tower = try shared.textTower(doc); + const table = try quant.detect(a, .{ .root = doc, .quantization = try shared.pickObject(doc, tower, "quantization") }); + const width = try table.width(""); + const spec = try shared.geometry(tower, width.bits, width.group); + const gen = if (generation) |g| (try std.json.parseFromSliceLeaky(std.json.Value, a, g, .{})) else null; + if (gen) |g| if (g != .object) return error.InvalidConfig; + const ids = try a.create([shared.checks.max_eos]u32); + const eos = try shared.checks.eos(ids, doc, tower, if (gen) |g| g.object else null, spec.vocab); + return .{ .arena = arena, .spec = spec, .quant = table, .tied = shared.isTied(doc, tower), .eos = eos }; + } +}; + +const sample = + \\{"model_type": "qwen3_5", "tie_word_embeddings": false, + \\ "quantization": {"group_size": 64, "bits": 4, "mode": "affine", + \\ "language_model.model.layers.0.mlp.gate": {"group_size": 32, "bits": 8}, + \\ "vision_tower.x": {"group_size": 64, "bits": 7}}, + \\ "text_config": {"hidden_size": 4096, "intermediate_size": 12288, "num_hidden_layers": 8, + \\ "num_attention_heads": 16, "num_key_value_heads": 4, "head_dim": 256, + \\ "linear_num_key_heads": 16, "linear_num_value_heads": 32, "linear_key_head_dim": 128, + \\ "linear_value_head_dim": 128, "linear_conv_kernel_dim": 4, "vocab_size": 248320, + \\ "rms_norm_eps": 1e-06, "full_attention_interval": 4, "mtp_num_hidden_layers": 1, "eos_token_id": 248044, + \\ "layer_types": ["linear_attention", "linear_attention", "linear_attention", "full_attention", + \\ "linear_attention", "linear_attention", "linear_attention", "full_attention"], + \\ "rope_parameters": {"rope_theta": 10000000, "partial_rotary_factor": 0.25}}} +; + +test "the config carries the geometry, the quantization width and the tying" { + var c = try Config.parse(std.testing.allocator, sample, null); + defer c.deinit(); + try std.testing.expectEqual(@as(usize, 4096), c.spec.hidden); + try std.testing.expectEqual(@as(u8, 4), c.spec.bits); + try std.testing.expectEqual(@as(u16, 64), c.spec.group); + try std.testing.expect(!c.tied); +} + +test "per-tensor widths override the global one, and a bad entry fails only when used" { + var c = try Config.parse(std.testing.allocator, sample, null); + defer c.deinit(); + try std.testing.expectEqual(Width{ .bits = 8, .group = 32 }, try c.quant.width("language_model.model.layers.0.mlp.gate")); + try std.testing.expectEqual(Width{ .bits = 4, .group = 64 }, try c.quant.width("language_model.model.layers.1.mlp.gate")); + try std.testing.expectError(error.UnsupportedQuantization, c.quant.width("vision_tower.x")); +} + +test "the Python loader's refusals of a quantization" { + const a = std.testing.allocator; + const bits = try std.mem.replaceOwned(u8, a, sample, "\"bits\": 4,", "\"bits\": 7,"); + defer a.free(bits); + try std.testing.expectError(error.UnsupportedQuantization, Config.parse(a, bits, null)); + const gptq = try std.mem.replaceOwned(u8, a, sample, "\"mode\": \"affine\"", "\"mode\": \"gptq\""); + defer a.free(gptq); + try std.testing.expectError(error.UnsupportedQuantization, Config.parse(a, gptq, null)); +} diff --git a/zig/src/families/qwen3_5/weights/experts.zig b/zig/src/families/qwen3_5/weights/experts.zig new file mode 100644 index 00000000000..16c7afa0153 --- /dev/null +++ b/zig/src/families/qwen3_5/weights/experts.zig @@ -0,0 +1,193 @@ +//! The Python loader's `_routed`, `_experts` and `_affine_side`: router rows and the stacked affine experts. + +const std = @import("std"); +const quant = @import("core").quant; +const table = @import("table.zig"); +const convert = quant.convert; +const config = @import("config.zig"); +const host = @import("host.zig"); +const projection = @import("projection.zig"); + +const Tensor = table.Tensor; +const Table = table.Table; +const DType = table.DType; +pub const Error = projection.Error; + +fn refuse(key: []const u8, what: []const u8) error{UnexpectedTensor} { + std.log.err("{s}: {s}", .{ key, what }); + return error.UnexpectedTensor; +} + +/// `_router_rows`: one router's rows [R, D] as fp32, a float tensor as stored or an affine group table unpacked. +fn routerRows(a: std.mem.Allocator, t: *const Table, key: []const u8) Error!struct { data: []f32, rows: usize, cols: usize } { + var buf: [256]u8 = undefined; + var other: [256]u8 = undefined; + const weight = try t.get(projection.join(&buf, &.{ key, ".weight" })); + if (convert.isFloat(weight.dtype)) { + if (weight.rank != 2) return refuse(key, "router weight must be (rows, hidden)"); + const wide = try convert.float32(a, weight); + const out = try a.alloc(f32, weight.numel()); + for (out, 0..) |*o, i| o.* = convert.load(.f32, wide.bytes, i); + return .{ .data = out, .rows = weight.shape[0], .cols = weight.shape[1] }; + } + const group = (try t.width(key)).group; + const scale = try t.get(projection.join(&buf, &.{ key, ".scales" })); + const bias = try t.get(projection.join(&other, &.{ key, ".biases" })); + const data = try quant.mlx.dequant(a, weight, scale, bias, group); + return .{ .data = data, .rows = weight.shape[0], .cols = scale.shape[1] * group }; +} + +/// The routed stack and the shared expert's tensor for one suffix, as `_shared_last` checks them. +const Pair = struct { mine: Tensor, one: Tensor }; + +fn pair(t: *const Table, stack_key: []const u8, shared: []const u8, suffix: []const u8) Error!Pair { + var b1: [256]u8 = undefined; + var b2: [256]u8 = undefined; + var mine = try t.get(projection.join(&b1, &.{ stack_key, suffix })); + var one = try t.get(projection.join(&b2, &.{ shared, suffix })); + if (mine.dtype == .u32) mine.dtype = .i32; + if (one.dtype == .u32) one.dtype = .i32; + if (one.rank == mine.rank and one.shape[0] == 1) { + one.rank -= 1; + one.shape = .{ one.shape[1], one.shape[2], one.shape[3], one.shape[4], 1 }; + } + if (mine.rank != one.rank + 1 or !std.mem.eql(usize, mine.shape[1..mine.rank], one.shape[0..one.rank])) return refuse(stack_key, "does not stack with the shared expert"); + return .{ .mine = mine, .one = one }; +} + +/// `fused` words, scales and biases of `srcs` stacked per expert, each expert's slices side by side along N. +fn stack(a: std.mem.Allocator, srcs: []const Pair, dtype: DType) Error!Tensor { + const count = srcs[0].mine.shape[0] + 1; + const rest = srcs[0].mine.shape[2]; + var rows: usize = 0; + for (srcs) |s| rows += s.mine.shape[1]; + const size = dtype.size(); + const out = try a.alloc(u8, count * rows * rest * size); + var at: usize = 0; + for (0..count) |e| for (srcs) |s| { + const n = s.mine.shape[1] * rest; + const src = if (e + 1 < count) s.mine.bytes[e * n * s.mine.dtype.size() ..][0 .. n * s.mine.dtype.size()] else s.one.bytes; + if (s.mine.dtype == dtype) { + @memcpy(out[at..][0..src.len], src); + } else for (0..n) |i| { + std.mem.writeInt(u32, out[at + 4 * i ..][0..4], @bitCast(convert.load(s.mine.dtype, src, i)), .little); + } + at += n * size; + }; + return .{ .dtype = dtype, .rank = 3, .shape = .{ count, rows, rest, 1, 1 }, .bytes = out }; +} + +/// The dtype the group tables of `srcs` share, or fp32 when they differ or the kernels do not read them as stored. +fn tableDtype(srcs: []const Pair, other: []const Pair) DType { + const first = srcs[0].mine.dtype; + for ([_][]const Pair{ srcs, other }) |list| for (list) |s| { + if (s.mine.dtype != first or s.one.dtype != first) return .f32; + }; + return if (convert.tableDtype(first)) first else .f32; +} + +/// One projection's tensors, checked as `_affine_side` does against (bits, group). +const Part = struct { words: Pair, scales: Pair, biases: Pair }; + +fn part(t: *const Table, stack_key: []const u8, shared: []const u8, w: config.Width) Error!Part { + const p: Part = .{ + .words = try pair(t, stack_key, shared, ".weight"), + .scales = try pair(t, stack_key, shared, ".scales"), + .biases = try pair(t, stack_key, shared, ".biases"), + }; + const words, const scale, const bias = .{ p.words.mine, p.scales.mine, p.biases.mine }; + if (words.dtype != .i32 or scale.rank != 3 or !std.mem.eql(usize, scale.shape[0..3], bias.shape[0..3])) return refuse(stack_key, "not an MLX affine expert stack"); + const k = scale.shape[2] * w.group; + if (words.shape[2] != k * w.bits / 32 or !std.mem.eql(usize, words.shape[0..2], scale.shape[0..2])) return refuse(stack_key, "packed stack does not fit K, bits and group"); + return p; +} + +fn side(a: std.mem.Allocator, parts: []const Part, w: config.Width) Error!host.Projection { + var words: [2]Pair = undefined; + var scales: [2]Pair = undefined; + var biases: [2]Pair = undefined; + for (parts, 0..) |p, i| { + words[i] = p.words; + scales[i] = p.scales; + biases[i] = p.biases; + } + const n = parts.len; + const dtype = tableDtype(scales[0..n], biases[0..n]); + return .{ .mlx = .{ + .words = try stack(a, words[0..n], .i32), + .scales = try stack(a, scales[0..n], dtype), + .biases = try stack(a, biases[0..n], dtype), + .bits = w.bits, + .group = w.group, + } }; +} + +/// `_experts`: a layer's E + 1 affine experts, the shared one last, gate and up fused per expert. +pub fn experts(a: std.mem.Allocator, t: *const Table, prefix: []const u8) Error!host.Experts { + var b: [4][256]u8 = undefined; + const mine = projection.join(&b[0], &.{ prefix, "switch_mlp." }); + const shared = projection.join(&b[1], &.{ prefix, "shared_expert." }); + if (!t.has(projection.join(&b[2], &.{ mine, "up_proj.weight" }))) { + if (t.has(projection.join(&b[2], &.{ mine, "up_proj.qweight" }))) return error.UnsupportedQuantization; + _ = try t.get(projection.join(&b[2], &.{ mine, "up_proj.weight" })); + } + const gated = t.has(projection.join(&b[2], &.{ mine, "gate_proj.weight" })); + var names: [3][2][256]u8 = undefined; + const keys = [3][]const u8{ "up_proj", "gate_proj", "down_proj" }; + var routed_keys: [3][]const u8 = undefined; + var shared_keys: [3][]const u8 = undefined; + for (keys, 0..) |k, i| { + routed_keys[i] = projection.join(&names[i][0], &.{ mine, k }); + shared_keys[i] = projection.join(&names[i][1], &.{ shared, k }); + } + const up_w = try t.width(routed_keys[0]); + const down_w = try t.width(routed_keys[2]); + if (gated and !std.meta.eql(try t.width(routed_keys[1]), up_w)) return refuse(mine, "gate and up differ in width"); + const up = try part(t, routed_keys[0], shared_keys[0], up_w); + const down = try part(t, routed_keys[2], shared_keys[2], down_w); + var fused_parts: [2]Part = undefined; + var n: usize = 0; + if (gated) { + fused_parts[0] = try part(t, routed_keys[1], shared_keys[1], up_w); + n = 1; + if (!std.mem.eql(usize, fused_parts[0].words.mine.shape[0..3], up.words.mine.shape[0..3])) return refuse(mine, "gate and up differ in shape"); + } + fused_parts[n] = up; + n += 1; + const fused = try side(a, fused_parts[0..n], up_w); + const d = try side(a, &.{down}, down_w); + return .{ + .fused = fused, + .gated = gated, + .down = d, + .width = up.words.mine.shape[1], + .dims = down.words.mine.shape[1], + .count = up.words.mine.shape[0] + 1, + }; +} + +/// `_routed`: router rows [E + 1, D] in bf16 (the shared expert's gate row last), widened once, and the experts. +pub fn routed(a: std.mem.Allocator, t: *const Table, prefix: []const u8, spec: config.Spec) Error!host.Routed { + var b: [2][256]u8 = undefined; + const gate = try routerRows(a, t, projection.join(&b[0], &.{ prefix, "gate" })); + const shared_gate = try routerRows(a, t, projection.join(&b[1], &.{ prefix, "shared_expert_gate" })); + const rows = gate.rows + shared_gate.rows; + if (gate.cols != shared_gate.cols or rows != spec.experts + 1 or gate.cols != spec.hidden) return refuse(prefix, "router rows do not fit E + 1 by hidden"); + const router = try a.alloc(u8, rows * gate.cols * 2); + const rows32 = try a.alloc(u8, rows * gate.cols * 4); + var at: usize = 0; + for ([_][]f32{ gate.data, shared_gate.data }) |part_rows| for (part_rows) |v| { + const half = convert.bf16(v); + std.mem.writeInt(u16, router[2 * at ..][0..2], half, .little); + std.mem.writeInt(u32, rows32[4 * at ..][0..4], @as(u32, half) << 16, .little); + at += 1; + }; + const ex = try experts(a, t, prefix); + if (ex.count != rows) return refuse(prefix, "router and experts disagree on E + 1"); + return .{ + .router = .{ .dtype = .bf16, .rank = 2, .shape = .{ rows, gate.cols, 1, 1, 1 }, .bytes = router }, + .rows32 = .{ .dtype = .f32, .rank = 2, .shape = .{ rows, gate.cols, 1, 1, 1 }, .bytes = rows32 }, + .experts = ex, + .top_k = spec.top_k, + }; +} diff --git a/zig/src/families/qwen3_5/weights/host.zig b/zig/src/families/qwen3_5/weights/host.zig new file mode 100644 index 00000000000..b0dc214f166 --- /dev/null +++ b/zig/src/families/qwen3_5/weights/host.zig @@ -0,0 +1,102 @@ +//! What the loader hands the GPU, still on the host: the Python TextModel's layers with the bytes its kernels read. + +const std = @import("std"); +const quant = @import("core").quant; +const table = @import("table.zig"); + +pub const Tensor = table.Tensor; + +/// A projection as its format read it from the checkpoint. +pub const Projection = quant.Host; + +/// A layer's E + 1 experts, shared last: `fused` is gate then up along N per expert, or up alone when not `gated`. +pub const Experts = struct { + fused: Projection, + gated: bool, + down: Projection, + /// The expert MLP's inner width (rows of the gate, and of the up). + width: usize, + /// The model width (rows of the down). + dims: usize, + /// E + 1. + count: usize, +}; + +/// The router rows [E + 1, D] with the shared gate last, in bf16 and widened to `rows32`; `remap` is a rank's own ids. +pub const Routed = struct { router: Tensor, rows32: Tensor, experts: Experts, top_k: usize, remap: ?Tensor = null }; + +pub const DenseMlp = struct { gate: Projection, up: Projection, down: Projection }; + +pub const Mlp = union(enum) { dense: DenseMlp, routed: Routed }; + +/// A gated delta-net layer. Norms, conv [channels, kernel], a_log, dt_bias and gnorm are fp32. +pub const Linear = struct { + input_norm: Tensor, + post_norm: Tensor, + qkv: Projection, + z: Projection, + a: Projection, + b: Projection, + conv: Tensor, + a_log: Tensor, + dt_bias: Tensor, + gnorm: Tensor, + out: Projection, + mlp: Mlp, +}; + +pub const Full = struct { + input_norm: Tensor, + post_norm: Tensor, + q: Projection, + k: Projection, + v: Projection, + o: Projection, + q_norm: Tensor, + k_norm: Tensor, + mlp: Mlp, +}; + +pub const Body = union(enum) { linear: Linear, full: Full }; + +/// One layer's tensors; `arena` holds what was converted or stacked, the rest points into the mapped files. +pub const Layer = struct { + arena: std.heap.ArenaAllocator, + body: Body, + + pub fn deinit(l: *Layer) void { + l.arena.deinit(); + l.* = undefined; + } +}; + +/// The MTP head: the Flash Next shape, or the Qwen3 one (`gated`) with input and post norms and an MLP. +pub const Mtp = struct { + arena: std.heap.ArenaAllocator, + /// The side files' table when the head came from them: the head's tensors point into its maps. + owned: ?table.Table = null, + io: std.Io, + fc_e_norm: Tensor, + fc_h_norm: Tensor, + fc_e: Projection, + fc_h: Projection, + q_norm: Tensor, + k_norm: Tensor, + q: Projection, + k: Projection, + v: Projection, + o: Projection, + final_norm: Tensor, + /// `null` ties with the main model's output head. + head: ?Projection, + input_norm: ?Tensor, + post_norm: ?Tensor, + mlp: ?Mlp, + gated: bool, + + pub fn deinit(m: *Mtp) void { + if (m.owned) |*t| t.close(m.io); + m.arena.deinit(); + m.* = undefined; + } +}; diff --git a/zig/src/families/qwen3_5/weights/projection.zig b/zig/src/families/qwen3_5/weights/projection.zig new file mode 100644 index 00000000000..c908dda33fb --- /dev/null +++ b/zig/src/families/qwen3_5/weights/projection.zig @@ -0,0 +1,47 @@ +//! The Python loader's `_packed`, `_float`, `_conv` and `_halves`: a tensor or a projection's, read and checked. + +const std = @import("std"); +const quant = @import("core").quant; +const table = @import("table.zig"); +const host = @import("host.zig"); + +const convert = quant.convert; +const Tensor = table.Tensor; +const Table = table.Table; +pub const Error = table.Error || convert.Error || error{UnexpectedTensor}; + +pub const join = quant.join; + +fn refuse(key: []const u8, what: []const u8) error{UnexpectedTensor} { + std.log.err("{s}: {s}", .{ key, what }); + return error.UnexpectedTensor; +} + +/// `_float`: the tensor widened to fp32. +pub fn float(a: std.mem.Allocator, t: *const Table, key: []const u8) Error!Tensor { + const src = try t.get(key); + if (!convert.isFloat(src.dtype)) return refuse(key, "not a floating tensor"); + return convert.float32(a, src); +} + +/// `_conv`: a depthwise conv weight as fp32 (channels, kernel); a trailing 1 is squeezed. +pub fn conv(a: std.mem.Allocator, t: *const Table, key: []const u8) Error!Tensor { + var w = try float(a, t, key); + if (w.rank == 3 and w.shape[2] == 1) { + w.rank = 2; + } else if (w.rank == 3 and w.shape[1] == 1) { + return refuse(key, "still in the unsanitized (channels, 1, kernel) layout"); + } + if (w.rank != 2) return refuse(key, "conv weight must be (channels, kernel)"); + return w; +} + +/// `_packed`: a projection in whichever format its tensors are in. +pub fn projection(a: std.mem.Allocator, t: *const Table, key: []const u8) !host.Projection { + return quant.read(a, t, key); +} + +/// `_halves`: a fused [embedding | hidden] projection split in two along K, words and group tables alike. +pub fn halves(a: std.mem.Allocator, fused: host.Projection) ![2]host.Projection { + return quant.halves(a, fused); +} diff --git a/zig/src/families/qwen3_5/weights/real_test.zig b/zig/src/families/qwen3_5/weights/real_test.zig new file mode 100644 index 00000000000..c86fe1bc0b8 --- /dev/null +++ b/zig/src/families/qwen3_5/weights/real_test.zig @@ -0,0 +1,56 @@ +//! The index check on a real checkpoint: TF_QWEN_DIR names a model directory; every tensor the loader reads resolves. + +const std = @import("std"); +const checkpoint = @import("checkpoint.zig"); +const host = @import("host.zig"); + +/// What a full pass over a checkpoint found. +pub const Summary = struct { layers: usize = 0, full: usize = 0, moe: usize = 0, mtp: bool = false, tied: bool = false, bytes: usize = 0 }; + +fn mlpBytes(m: host.Mlp) usize { + return switch (m) { + .dense => |d| d.gate.bytes() + d.up.bytes() + d.down.bytes(), + .routed => |r| r.router.bytes.len + r.rows32.bytes.len + r.experts.fused.bytes() + r.experts.down.bytes(), + }; +} + +/// Reads and checks every layer, the embedding, the head and the MTP layer of the checkpoint in `dir`. +pub fn run(gpa: std.mem.Allocator, io: std.Io, dir: []const u8) !Summary { + var ck = try checkpoint.Checkpoint.open(gpa, io, dir); + defer ck.close(); + var sum: Summary = .{ .tied = ck.config.tied }; + var scratch: std.heap.ArenaAllocator = .init(gpa); + defer scratch.deinit(); + const embed = try ck.embed(scratch.allocator()); + sum.bytes += embed.bytes(); + _ = try ck.finalNorm(scratch.allocator()); + if (try ck.head(scratch.allocator())) |h| sum.bytes += h.bytes(); + for (0..ck.spec().n_layers) |i| { + var layer = try ck.layer(i); + defer layer.deinit(); + sum.layers += 1; + const mlp = switch (layer.body) { + .full => |f| blk: { + sum.full += 1; + break :blk f.mlp; + }, + .linear => |l| l.mlp, + }; + if (mlp == .routed) sum.moe += 1; + sum.bytes += mlpBytes(mlp); + } + if (try ck.mtp()) |m| { + var head = m; + defer head.deinit(); + sum.mtp = true; + if (head.mlp) |x| sum.bytes += mlpBytes(x); + } + return sum; +} + +test "the real checkpoint (TF_QWEN_DIR) resolves every tensor with consistent shapes" { + const dir = std.testing.environ.getPosix("TF_QWEN_DIR") orelse return error.SkipZigTest; + const sum = try run(std.testing.allocator, std.testing.io, dir); + std.debug.print("qwen35 index: {d} layers ({d} full attention, {d} MoE), tied head {}, MTP {}, {d} MiB of projections and MLPs\n", .{ sum.layers, sum.full, sum.moe, sum.tied, sum.mtp, sum.bytes >> 20 }); + try std.testing.expect(sum.layers > 0); +} diff --git a/zig/src/families/qwen3_5/weights/shard.zig b/zig/src/families/qwen3_5/weights/shard.zig new file mode 100644 index 00000000000..e09e502bc97 --- /dev/null +++ b/zig/src/families/qwen3_5/weights/shard.zig @@ -0,0 +1,81 @@ +//! One safetensors file mapped read-only; tensors above core's max rank and unnamed dtypes stay out of its index. + +const std = @import("std"); +const Io = std.Io; +const st = @import("core").safetensors; + +pub const Tensor = st.Tensor; + +pub const Shard = struct { + file: Io.File, + map: Io.File.MemoryMap, + data: usize, + names: st.Header, + arena: std.heap.ArenaAllocator, + + pub fn open(gpa: std.mem.Allocator, io: Io, path: []const u8) !Shard { + var file = try Io.Dir.cwd().openFile(io, path, .{}); + errdefer file.close(io); + const len: usize = @intCast(try file.length(io)); + if (len < 8) return error.BadSafetensors; + var map = try Io.File.MemoryMap.create(io, file, .{ .len = len, .protection = .{ .read = true, .write = false }, .populate = false }); + errdefer map.destroy(io); + const header_len: usize = @intCast(std.mem.readInt(u64, map.memory[0..8], .little)); + if (header_len > len - 8) return error.BadSafetensors; + var arena: std.heap.ArenaAllocator = .init(gpa); + errdefer arena.deinit(); + const names = try parse(arena.allocator(), map.memory[8..][0..header_len], len - 8 - header_len); + return .{ .file = file, .map = map, .data = 8 + header_len, .names = names, .arena = arena }; + } + + pub fn close(s: *Shard, io: Io) void { + s.map.destroy(io); + s.file.close(io); + s.arena.deinit(); + s.* = undefined; + } + + pub fn get(s: *const Shard, name: []const u8) ?Tensor { + const e = s.names.get(name) orelse return null; + return .{ .dtype = e.dtype, .rank = e.rank, .shape = e.shape, .bytes = s.map.memory[s.data + e.begin .. s.data + e.end] }; + } +}; + +/// core's `parseHeader` without its refusals of rank and dtype; sizes and ranges are still checked. +fn parse(arena: std.mem.Allocator, json: []const u8, data_len: usize) !st.Header { + const parsed = try std.json.parseFromSliceLeaky(std.json.Value, arena, json, .{}); + var out: st.Header = .empty; + var it = parsed.object.iterator(); + while (it.next()) |kv| { + if (std.mem.eql(u8, kv.key_ptr.*, "__metadata__")) continue; + const o = kv.value_ptr.object; + const dtype = st.DType.parse(o.get("dtype").?.string) orelse continue; + const shape = o.get("shape").?.array.items; + if (shape.len > st.max_rank) continue; + var e: st.Entry = .{ .dtype = dtype, .rank = @intCast(shape.len), .shape = @splat(1), .begin = 0, .end = 0 }; + var n: usize = dtype.size(); + for (shape, 0..) |d, i| { + e.shape[i] = @intCast(d.integer); + n *= e.shape[i]; + } + const offs = o.get("data_offsets").?.array.items; + e.begin = @intCast(offs[0].integer); + e.end = @intCast(offs[1].integer); + if (e.end < e.begin or e.end - e.begin != n or e.end > data_len) return error.BadSafetensors; + try out.put(arena, kv.key_ptr.*, e); + } + return out; +} + +test "a tensor above the max rank and an unknown dtype are left out" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const json = + \\{"a": {"dtype": "U32", "shape": [2], "data_offsets": [0, 8]}, + \\ "patch": {"dtype": "BF16", "shape": [1, 1, 1, 1, 1, 1], "data_offsets": [8, 10]}, + \\ "q9": {"dtype": "Q9_UNKNOWN", "shape": [2], "data_offsets": [10, 12]}} + ; + const h = try parse(arena.allocator(), json, 12); + try std.testing.expectEqual(@as(usize, 1), h.count()); + try std.testing.expect(h.contains("a")); +} diff --git a/zig/src/families/qwen3_5/weights/slicing.zig b/zig/src/families/qwen3_5/weights/slicing.zig new file mode 100644 index 00000000000..9c458f67abd --- /dev/null +++ b/zig/src/families/qwen3_5/weights/slicing.zig @@ -0,0 +1,124 @@ +const std = @import("std"); +const config = @import("config.zig"); +const host = @import("host.zig"); + +const quant = @import("core").quant; +const Allocator = std.mem.Allocator; +const takeRows = quant.slice.takeRows; +const even = quant.slice.even; + +pub const Error = error{ UnevenSplit, KvHeads } || Allocator.Error; + +pub const Rank = quant.Rank; +const Span = quant.Span; + +/// The spec as a rank sees it: its heads and value heads (the vocabulary stays whole; the head's rows are split). +pub fn localSpec(s: config.Spec, r: Rank) Error!config.Spec { + var out = s; + out.heads = try even(s.heads, r.world, "heads"); + out.key_heads = try even(s.key_heads, r.world, "key_heads"); + out.value_heads = try even(s.value_heads, r.world, "value_heads"); + _ = try even(s.vocab, r.world, "vocab"); + out.kv_heads = @max(1, s.kv_heads / r.world); + return out; +} + +/// `_rows`: output rows `spans` of a projection, the share of a column-split one. +fn sliceRows(a: Allocator, p: host.Projection, spans: []const Span) Error!host.Projection { + return quant.sliceRows(a, p, spans); +} + +/// `_cols`: one rank's whole input groups of a row-split projection, whose fp32 outputs the ranks sum. +fn cols(a: Allocator, p: host.Projection, r: Rank, what: []const u8) Error!host.Projection { + return quant.sliceCols(a, p, r, what); +} + +/// This rank's rows of each segment of a concatenated output (q | k | v), each segment split evenly. +fn segments(widths: []const usize, r: Rank, out: []Span, what: []const u8) Error![]const Span { + var base: usize = 0; + for (widths, out[0..widths.len]) |w, *span| { + const part = try even(w, r.world, what); + span.* = .{ .from = base + r.rank * part, .to = base + (r.rank + 1) * part }; + base += w; + } + return out[0..widths.len]; +} + +/// This rank's k or v rows; with fewer KV heads than ranks each head is kept by its query ranks. +fn kvSpan(width: usize, kv_heads: usize, r: Rank, out: []Span) Error![]const Span { + if (kv_heads >= r.world) return segments(&.{width}, r, out, "kv rows"); + if (r.world % kv_heads != 0) return error.KvHeads; + const head = r.rank / (r.world / kv_heads); + const part = width / kv_heads; + out[0] = .{ .from = head * part, .to = (head + 1) * part }; + return out[0..1]; +} + +/// One layer's tensors for rank `r`, cut in place (`l.arena` holds the copies). `s` is the whole model's spec. +pub fn layer(l: *host.Layer, s: config.Spec, r: Rank) Error!void { + const a = l.arena.allocator(); + var buf: [3]Span = undefined; + switch (l.body) { + .full => |*f| { + f.q = try sliceRows(a, f.q, try segments(&.{s.heads * s.head_dim * 2}, r, &buf, "q_proj")); + const kv = s.kv_heads * s.head_dim; + f.k = try sliceRows(a, f.k, try kvSpan(kv, s.kv_heads, r, &buf)); + f.v = try sliceRows(a, f.v, try kvSpan(kv, s.kv_heads, r, &buf)); + f.o = try cols(a, f.o, r, "o_proj groups"); + try mlp(a, &f.mlp, r); + }, + .linear => |*x| { + const qkv = try segments(&.{ s.keyWidth(), s.keyWidth(), s.valueWidth() }, r, &buf, "in_proj_qkv"); + x.qkv = try sliceRows(a, x.qkv, qkv); + x.conv = try takeRows(a, x.conv, qkv); + x.z = try sliceRows(a, x.z, try segments(&.{s.valueWidth()}, r, &buf, "in_proj_z")); + const heads = try segments(&.{s.value_heads}, r, &buf, "value heads"); + x.a = try sliceRows(a, x.a, heads); + x.b = try sliceRows(a, x.b, heads); + x.a_log = try takeRows(a, x.a_log, heads); + x.dt_bias = try takeRows(a, x.dt_bias, heads); + x.out = try cols(a, x.out, r, "out_proj groups"); + try mlp(a, &x.mlp, r); + }, + } +} + +fn mlp(a: Allocator, m: *host.Mlp, r: Rank) Error!void { + switch (m.*) { + .dense => |*d| { + var buf: [1]Span = undefined; + const spans = try segments(&.{d.gate.rows()}, r, &buf, "mlp"); + d.gate = try sliceRows(a, d.gate, spans); + d.up = try sliceRows(a, d.up, spans); + d.down = try cols(a, d.down, r, "mlp.down_proj groups"); + }, + .routed => |*x| try routed(a, x, r), + } +} + +/// A rank's contiguous routed experts, the shared one on rank 0, and the remap to its own ids (-1: another rank's). +fn routed(a: Allocator, x: *host.Routed, r: Rank) Error!void { + const total = x.experts.count - 1; + const part = try even(total, r.world, "experts"); + x.experts.fused = try quant.sliceStack(a, x.experts.fused, r, part); + x.experts.down = try quant.sliceStack(a, x.experts.down, r, part); + x.experts.count = part + @intFromBool(r.rank == 0); + const remap = try a.alloc(i32, total + 1); + @memset(remap, -1); + for (0..part) |i| remap[r.rank * part + i] = @intCast(i); + if (r.rank == 0) remap[total] = @intCast(part); + x.remap = .{ .dtype = .i32, .rank = 1, .shape = .{ total + 1, 1, 1, 1, 1 }, .bytes = std.mem.sliceAsBytes(remap) }; +} + +/// The output head's rows for rank `r`: its share of the vocabulary. +pub fn vocabRows(a: Allocator, p: host.Projection, vocab: usize, r: Rank) Error!host.Projection { + var buf: [1]Span = undefined; + return sliceRows(a, p, try segments(&.{vocab}, r, &buf, "vocab")); +} + +test "a kv head is kept by its query ranks" { + var buf: [1]Span = undefined; + const spans = try kvSpan(256, 2, .{ .rank = 3, .world = 4 }, &buf); + try std.testing.expectEqual(Span{ .from = 128, .to = 256 }, spans[0]); + try std.testing.expectError(error.KvHeads, kvSpan(256, 3, .{ .rank = 0, .world = 4 }, &buf)); +} diff --git a/zig/src/families/qwen3_5/weights/table.zig b/zig/src/families/qwen3_5/weights/table.zig new file mode 100644 index 00000000000..0bb3936a081 --- /dev/null +++ b/zig/src/families/qwen3_5/weights/table.zig @@ -0,0 +1,136 @@ +//! One tensor table over a checkpoint's safetensors files, with the Python loader's `_Shards` key stripping and widths. + +const std = @import("std"); +const Io = std.Io; +const st = @import("core").safetensors; +const formats = @import("core").quant; +const config = @import("config.zig"); + +const Shard = @import("shard.zig").Shard; +pub const Tensor = st.Tensor; +pub const DType = st.DType; +pub const Error = error{ MissingTensor, NoSafetensors } || config.Error || std.mem.Allocator.Error; + +const Where = struct { file: usize, stored: []const u8 }; + +pub const Table = struct { + gpa: std.mem.Allocator, + files: []Shard, + where: std.StringHashMapUnmanaged(Where) = .empty, + /// A key prefix the table drops (`language_model.`), as `_Shards(strip=)`. + strip: []const u8, + quant: formats.Config, + + /// Maps `paths` (later files win a repeated name, as the Python dict does). + pub fn open(gpa: std.mem.Allocator, io: Io, paths: []const []const u8, strip: []const u8, quant: formats.Config) !Table { + const files = try gpa.alloc(Shard, paths.len); + var opened: usize = 0; + errdefer { + for (files[0..opened]) |*f| f.close(io); + gpa.free(files); + } + for (paths) |p| { + files[opened] = try Shard.open(gpa, io, p); + opened += 1; + } + var t: Table = .{ .gpa = gpa, .files = files, .strip = strip, .quant = quant }; + errdefer t.where.deinit(gpa); + for (files, 0..) |*f, i| for (f.names.keys()) |key| { + const short = if (strip.len > 0 and std.mem.startsWith(u8, key, strip)) key[strip.len..] else key; + try t.where.put(gpa, short, .{ .file = i, .stored = key }); + }; + return t; + } + + pub fn close(t: *Table, io: Io) void { + for (t.files) |*f| f.close(io); + t.gpa.free(t.files); + t.where.deinit(t.gpa); + t.* = undefined; + } + + pub fn has(t: *const Table, key: []const u8) bool { + return t.where.contains(key); + } + + /// The tensor under `key`; a missing one is `error.MissingTensor`, logged by name. + pub fn get(t: *const Table, key: []const u8) Error!Tensor { + const w = t.where.get(key) orelse { + std.log.err("checkpoint has no tensor {s}", .{key}); + return error.MissingTensor; + }; + return t.files[w.file].get(w.stored).?; + } + + /// Every key of the table (stripped names). + pub fn keys(t: *const Table) []const []const u8 { + return t.where.keys(); + } + + /// The tensor's own width when the config names it (`key`, then the stripped prefix back on), else the global one. + pub fn width(t: *const Table, key: []const u8) config.Error!formats.mlx.Width { + const q = switch (t.quant) { + .mlx => |m| m, + .dense => return error.UnsupportedQuantization, + }; + if (q.overrides.get(key)) |w| return w orelse error.UnsupportedQuantization; + if (t.strip.len > 0) { + var buf: [512]u8 = undefined; + const full = std.fmt.bufPrint(&buf, "{s}{s}", .{ t.strip, key }) catch return q.global; + if (q.overrides.get(full)) |w| return w orelse error.UnsupportedQuantization; + } + return q.global; + } +}; + +/// The checkpoint's safetensors paths, sorted: the model's own files, and the `mtp*.safetensors` side files. +pub const Files = struct { + arena: std.heap.ArenaAllocator, + model: []const []const u8, + side: []const []const u8, + + pub fn deinit(f: *Files) void { + f.arena.deinit(); + f.* = undefined; + } + + /// `root.glob("*.safetensors")`: a file whose name holds "mtp" is not the model's; `mtp*` ones are the side files. + pub fn list(gpa: std.mem.Allocator, io: Io, dir: []const u8) !Files { + var arena: std.heap.ArenaAllocator = .init(gpa); + errdefer arena.deinit(); + const a = arena.allocator(); + var model: std.ArrayList([]const u8) = .empty; + var side: std.ArrayList([]const u8) = .empty; + var d = try Io.Dir.cwd().openDir(io, dir, .{ .iterate = true }); + defer d.close(io); + var it = d.iterate(); + while (try it.next(io)) |e| { + if (e.kind != .file and e.kind != .sym_link) continue; + if (!std.mem.endsWith(u8, e.name, ".safetensors")) continue; + const path = try std.fs.path.join(a, &.{ dir, e.name }); + if (std.mem.startsWith(u8, e.name, "mtp")) try side.append(a, path); + if (!containsLower(e.name, "mtp")) try model.append(a, path); + } + const less = struct { + fn f(_: void, x: []const u8, y: []const u8) bool { + return std.mem.order(u8, x, y) == .lt; + } + }.f; + std.mem.sort([]const u8, model.items, {}, less); + std.mem.sort([]const u8, side.items, {}, less); + return .{ .arena = arena, .model = model.items, .side = side.items }; + } +}; + +fn containsLower(name: []const u8, needle: []const u8) bool { + var i: usize = 0; + while (i + needle.len <= name.len) : (i += 1) { + if (std.ascii.eqlIgnoreCase(name[i..][0..needle.len], needle)) return true; + } + return false; +} + +test "mtp in a file name keeps it out of the model's files" { + try std.testing.expect(containsLower("Model-MTP-4bit.safetensors", "mtp")); + try std.testing.expect(!containsLower("model-00001-of-00004.safetensors", "mtp")); +} diff --git a/zig/src/hip/admission.zig b/zig/src/hip/admission.zig new file mode 100644 index 00000000000..2082b5b49de --- /dev/null +++ b/zig/src/hip/admission.zig @@ -0,0 +1,65 @@ +//! What the HIP engine may serve: the CUDA path's memory rules (cuda_memory.zig) and the window and weights it reads. +const std = @import("std"); +const memory = @import("cuda_memory"); +const Allocator = std.mem.Allocator; + +pub const MemInfo = memory.MemInfo; +pub const Pool = memory.Pool; +pub const meminfo = memory.meminfo; +pub const reserveBytes = memory.reserveBytes; +pub const limitBytes = memory.limitBytes; +pub const admit = memory.admit; +pub const counts = memory.counts; + +/// The model's window (config.json's max_position_embeddings, text_config's first), 0 when it names none. +pub fn modelContext(a: Allocator, io: std.Io, dir: []const u8) i64 { + const path = std.fs.path.join(a, &.{ dir, "config.json" }) catch return 0; + const bytes = std.Io.Dir.cwd().readFileAlloc(io, path, a, .limited(16 << 20)) catch return 0; + const doc = std.json.parseFromSliceLeaky(std.json.Value, a, bytes, .{}) catch return 0; + if (doc != .object) return 0; + const text = if (doc.object.get("text_config")) |t| (if (t == .object) t else doc) else doc; + const limit = text.object.get("max_position_embeddings") orelse doc.object.get("max_position_embeddings") orelse return 0; + return if (limit == .integer and limit.integer > 0) limit.integer else 0; +} + +/// Prompt plus reply tokens a request may use: --context (0: the model's window), else the family default within it. +pub fn contextWindow(requested: ?i64, native: i64, default: i64) error{ Negative, NoNative, PastNative }!i64 { + const r = requested orelse return if (native > 0) @min(default, native) else default; + if (r < 0) return error.Negative; + if (r == 0) return if (native > 0) native else error.NoNative; + if (native > 0 and r > native) return error.PastNative; + return r; +} + +/// The bytes of the checkpoint's safetensors files: what its weights need on the device, near enough to refuse early. +pub fn weightBytes(io: std.Io, dir: []const u8) u64 { + var d = std.Io.Dir.cwd().openDir(io, dir, .{ .iterate = true }) catch return 0; + defer d.close(io); + var total: u64 = 0; + var it = d.iterate(); + while (it.next(io) catch null) |e| { + if (!std.mem.endsWith(u8, e.name, ".safetensors")) continue; + const st = d.statFile(io, e.name, .{}) catch continue; + total += st.size; + } + return total; +} + +/// A /proc file's text, streamed: procfs reports size 0, and a positional read (readFileAlloc) stops there. +pub fn procText(a: Allocator, io: std.Io, path: []const u8) ?[]u8 { + var file = std.Io.Dir.cwd().openFile(io, path, .{}) catch return null; + defer file.close(io); + var buf: [4096]u8 = undefined; + var r = file.readerStreaming(io, &buf); + return r.interface.allocRemaining(a, .limited(1 << 20)) catch null; +} + +test "context windows: the family default inside the model's, 0 for the model's, never past it" { + try std.testing.expectEqual(@as(i64, 16384), try contextWindow(null, 262144, 16384)); + try std.testing.expectEqual(@as(i64, 4096), try contextWindow(null, 4096, 16384)); + try std.testing.expectEqual(@as(i64, 262144), try contextWindow(0, 262144, 16384)); + try std.testing.expectEqual(@as(i64, 65536), try contextWindow(65536, 262144, 16384)); + try std.testing.expectError(error.PastNative, contextWindow(300000, 262144, 16384)); + try std.testing.expectError(error.Negative, contextWindow(-5, 262144, 16384)); + try std.testing.expectError(error.NoNative, contextWindow(0, 0, 16384)); +} diff --git a/zig/src/hip/admission_tests.zig b/zig/src/hip/admission_tests.zig index 9d55184ec7e..3853a524a49 100644 --- a/zig/src/hip/admission_tests.zig +++ b/zig/src/hip/admission_tests.zig @@ -11,6 +11,9 @@ test { _ = @import("runtime.zig"); _ = @import("launch.zig"); _ = @import("graph.zig"); + _ = @import("arena.zig"); + _ = @import("launches.zig"); + _ = @import("ops/ops.zig"); _ = @import("context.zig").Context.init; _ = @import("stream.zig").Stream.init; _ = @import("memory.zig").DeviceBuffer.alloc; diff --git a/zig/src/hip/arena.zig b/zig/src/hip/arena.zig new file mode 100644 index 00000000000..ecd192fc66a --- /dev/null +++ b/zig/src/hip/arena.zig @@ -0,0 +1,74 @@ +//! A forward's scratch handed out front to back and reset per forward, so a captured graph replays the same addresses. + +const std = @import("std"); +const runtime = @import("runtime.zig"); +const DeviceBuffer = @import("memory.zig").DeviceBuffer; + +pub const Arena = struct { + /// Null for a counting arena. + buf: ?DeviceBuffer, + base: u64, + len: usize, + used: usize = 0, + peak: usize = 0, + + pub fn init(r: *const runtime.Runtime, bytes: usize) runtime.Error!Arena { + const buf = try DeviceBuffer.alloc(r, bytes); + return .{ .buf = buf, .base = @intFromPtr(buf.ptr), .len = bytes }; + } + + /// An arena with no memory behind it, for a forward on the counting stream: its peak is what the forward takes. + pub fn counting() Arena { + return .{ .buf = null, .base = 1 << 40, .len = 1 << 60 }; + } + + pub fn deinit(self: *Arena) void { + if (self.buf) |*b| b.free(); + self.* = undefined; + } + + /// `bytes` 256-byte aligned; refused past the end (the caller sized the arena for its largest forward). + pub fn take(self: *Arena, bytes: usize) error{OutOfDeviceMemory}!u64 { + const at = std.mem.alignForward(usize, self.used, 256); + if (at + bytes > self.len) { + std.log.err("scratch arena of {d} bytes cannot take {d} more at {d}", .{ self.len, bytes, at }); + return error.OutOfDeviceMemory; + } + self.used = at + bytes; + self.peak = @max(self.peak, self.used); + return self.base + at; + } + + /// `n` values of `T`. + pub fn of(self: *Arena, comptime T: type, n: usize) error{OutOfDeviceMemory}!u64 { + return self.take(n * @sizeOf(T)); + } + + pub fn reset(self: *Arena) void { + self.used = 0; + } + + /// The current mark, to hand scratch back after a step that needs it only briefly. + pub fn mark(self: *const Arena) usize { + return self.used; + } + + pub fn release(self: *Arena, at: usize) void { + std.debug.assert(at <= self.used); + self.used = at; + } +}; + +test "scratch comes front to back, 256-byte aligned, and is refused past the end" { + var a = Arena.counting(); + a.len = 1000; + try std.testing.expectEqual(@as(u64, 1 << 40), try a.take(10)); + try std.testing.expectEqual(@as(u64, (1 << 40) + 256), try a.of(f32, 4)); + const m = a.mark(); + _ = try a.take(300); + a.release(m); + try std.testing.expectEqual(@as(usize, 272), a.used); + try std.testing.expectEqual(@as(usize, 512 + 300), a.peak); + a.reset(); + try std.testing.expectEqual(@as(usize, 0), a.used); +} diff --git a/zig/src/hip/collective.zig b/zig/src/hip/collective.zig new file mode 100644 index 00000000000..a24c55aba88 --- /dev/null +++ b/zig/src/hip/collective.zig @@ -0,0 +1,127 @@ +//! What a tensor-parallel engine asks of its ranks: collectives on its streams, and rank 0's words to the others. + +const std = @import("std"); +const abi = @import("abi.zig"); + +pub const Error = error{CollectiveFailed}; +pub const LinkError = error{LinkFailed} || std.mem.Allocator.Error; +/// Why a rank could not join its group: no tensor parallelism in this build, no RCCL, or the link between the ranks. +pub const JoinError = error{ NoTensorParallel, NoRccl, NoId, SocketFailed, BindFailed, ConnectFailed, LinkClosed, BadRank, MixedGpus } || std.mem.Allocator.Error; + +/// The join of a build without a collectives backend: one rank only. +pub fn noGroup(_: std.mem.Allocator, _: std.Io, _: u32, _: u32, _: []const u8, _: u16, _: @import("caps.zig").Caps, _: *@import("policy.zig").Policy) JoinError!Group { + return error.NoTensorParallel; +} + +/// The element types the forward moves, in RCCL's numbering. +pub const Dtype = enum(c_int) { u8 = 1, i32 = 2, i64 = 4, f16 = 6, f32 = 7, bf16 = 9 }; + +/// One rank's communicator. A collective queues on its stream and waits for every rank's matching call. +pub const Comm = struct { + ptr: *anyopaque, + vtable: *const VTable, + rank: usize, + world: usize, + + pub const VTable = struct { + all_reduce: *const fn (ptr: *anyopaque, send: u64, recv: u64, n: usize, dtype: Dtype, stream: abi.Stream) Error!void, + all_gather: *const fn (ptr: *anyopaque, send: u64, recv: u64, n: usize, dtype: Dtype, stream: abi.Stream) Error!void, + broadcast: *const fn (ptr: *anyopaque, send: u64, recv: u64, n: usize, dtype: Dtype, root: usize, stream: abi.Stream) Error!void, + close: *const fn (ptr: *anyopaque) void, + }; + + /// `recv` = the ranks' `send` summed, `n` values of `dtype`. + pub fn allReduce(c: Comm, send: u64, recv: u64, n: usize, dtype: Dtype, stream: abi.Stream) Error!void { + return c.vtable.all_reduce(c.ptr, send, recv, n, dtype, stream); + } + + /// `recv` (world * n values) = every rank's `send` (n values) in rank order. + pub fn allGather(c: Comm, send: u64, recv: u64, n: usize, dtype: Dtype, stream: abi.Stream) Error!void { + return c.vtable.all_gather(c.ptr, send, recv, n, dtype, stream); + } + + /// `root`'s `send` into every rank's `recv`, `n` values. + pub fn broadcast(c: Comm, send: u64, recv: u64, n: usize, dtype: Dtype, root: usize, stream: abi.Stream) Error!void { + return c.vtable.broadcast(c.ptr, send, recv, n, dtype, root, stream); + } + + pub fn close(c: Comm) void { + c.vtable.close(c.ptr); + } +}; + +/// Rank 0's channel to the others: it sends each step, a follower takes them in order. +pub const Link = struct { + ptr: *anyopaque, + vtable: *const VTable, + + pub const VTable = struct { + send: *const fn (ptr: *anyopaque, words: []const u32) LinkError!void, + recv: *const fn (ptr: *anyopaque, gpa: std.mem.Allocator, out: *std.ArrayList(u32)) LinkError!void, + }; + + /// Rank 0: `words` to every follower. + pub fn send(l: Link, words: []const u32) LinkError!void { + return l.vtable.send(l.ptr, words); + } + + /// A follower: rank 0's next message into `out` (cleared first). + pub fn recv(l: Link, gpa: std.mem.Allocator, out: *std.ArrayList(u32)) LinkError!void { + return l.vtable.recv(l.ptr, gpa, out); + } +}; + +/// What a rank holds once it joined its group: the link, and its communicator opened when the engine's GPU is current. +pub const Group = struct { + ptr: *anyopaque, + vtable: *const VTable, + rank: usize, + world: usize, + + pub const VTable = struct { + link: *const fn (ptr: *anyopaque) Link, + open: *const fn (ptr: *anyopaque) Error!Comm, + close: *const fn (ptr: *anyopaque, gpa: std.mem.Allocator) void, + }; + + pub fn link(g: Group) Link { + return g.vtable.link(g.ptr); + } + + /// This rank's communicator: blocks until every rank has opened its own; the engine's device is current. + pub fn open(g: Group) Error!Comm { + return g.vtable.open(g.ptr); + } + + pub fn close(g: Group, gpa: std.mem.Allocator) void { + g.vtable.close(g.ptr, gpa); + } +}; + +test "a comm forwards each collective to its implementation" { + const Fake = struct { + calls: [3]usize = .{ 0, 0, 0 }, + closed: bool = false, + fn reduce(ptr: *anyopaque, _: u64, _: u64, _: usize, _: Dtype, _: abi.Stream) Error!void { + @as(*@This(), @ptrCast(@alignCast(ptr))).calls[0] += 1; + } + fn gather(ptr: *anyopaque, _: u64, _: u64, _: usize, _: Dtype, _: abi.Stream) Error!void { + @as(*@This(), @ptrCast(@alignCast(ptr))).calls[1] += 1; + } + fn cast(ptr: *anyopaque, _: u64, _: u64, _: usize, _: Dtype, _: usize, _: abi.Stream) Error!void { + @as(*@This(), @ptrCast(@alignCast(ptr))).calls[2] += 1; + } + fn shut(ptr: *anyopaque) void { + @as(*@This(), @ptrCast(@alignCast(ptr))).closed = true; + } + }; + var f: Fake = .{}; + const c: Comm = .{ .ptr = &f, .vtable = &.{ .all_reduce = Fake.reduce, .all_gather = Fake.gather, .broadcast = Fake.cast, .close = Fake.shut }, .rank = 1, .world = 2 }; + try c.allReduce(0, 0, 1, .f32, null); + try c.allGather(0, 0, 1, .bf16, null); + try c.allGather(0, 0, 1, .bf16, null); + try c.broadcast(0, 0, 1, .i32, 0, null); + c.close(); + try std.testing.expectEqual([3]usize{ 1, 2, 1 }, f.calls); + try std.testing.expect(f.closed); +} diff --git a/zig/src/hip/device.zig b/zig/src/hip/device.zig new file mode 100644 index 00000000000..beb3b890875 --- /dev/null +++ b/zig/src/hip/device.zig @@ -0,0 +1,70 @@ +//! The GPU a rank serves on and what the run may use there, chosen once by whoever opens an engine. + +const std = @import("std"); +const runtime = @import("runtime.zig"); +const kernels = @import("kernels.zig"); +const Caps = @import("caps.zig").Caps; +const Policy = @import("policy.zig").Policy; +const Group = @import("collective.zig").Group; + +pub const Device = struct { + /// The ordinal among the visible cards. + index: c_int, + caps: Caps, + /// Rank 0's policy; the other ranks adopt it when they join the group. + policy: Policy, + /// The tensor-parallel group this rank belongs to (null: one rank). + group: ?Group = null, + + /// The card of `rank`: with every card visible rank r takes card r, with one card a process that card. + pub fn ordinal(rank: u32) c_int { + var r = runtime.Runtime.open() catch return 0; + defer r.close(); + const count = r.deviceCount() catch return 0; + return if (count > 0) @intCast(rank % @as(u32, @intCast(count))) else 0; + } + + /// The caps of the card at `index` when this build's kernels were compiled for it; refused otherwise. + pub fn kernelCaps(r: *runtime.Runtime, index: c_int) error{ UnsupportedGpu, KernelArch }!Caps { + var buf: [64]u8 = undefined; + const arch = archName(r, index, &buf) catch return error.UnsupportedGpu; + const caps = Caps.of(arch) orelse return error.UnsupportedGpu; + const end = std.mem.indexOfScalar(u8, arch, ':') orelse arch.len; + if (!std.mem.eql(u8, arch[0..end], kernels.arch)) { + std.log.err("this GPU is {s}; this build's kernels are for {s} (-Dhip-arch)", .{ arch[0..end], kernels.arch }); + return error.KernelArch; + } + return caps; + } + + /// What every rank of a group must share: the GPU its kernels were built for. + pub fn groupId(caps: Caps) u32 { + return std.hash.Crc32.hash(kernels.arch) ^ @as(u32, @backingInt(caps.generation)); + } + + /// What the card at `index` can do, or null when it is no usable GPU or one outside the caps table. + pub fn capsOf(index: c_int) ?Caps { + var r = runtime.Runtime.open() catch return null; + defer r.close(); + var buf: [64]u8 = undefined; + const arch = archName(&r, index, &buf) catch return null; + return Caps.of(arch); + } + + /// The card's gfx name ("gfx1100", "gfx906:sramecc+:xnack-"), found in its properties record by its prefix. + pub fn archName(r: *runtime.Runtime, index: c_int, out: []u8) runtime.Error![]const u8 { + const Properties = *const fn (*anyopaque, c_int) callconv(.c) c_int; + const get = r.lib.lookup(Properties, "hipGetDevicePropertiesR0600") orelse return error.MissingSymbol; + var props: [16384]u8 align(8) = @splat(0); + try runtime.check(get(&props, index)); + var at: usize = 256; + while (at + 4 < props.len) : (at += 1) { + if (!std.mem.startsWith(u8, props[at..], "gfx") or !std.ascii.isHex(props[at + 3])) continue; + const text = std.mem.sliceTo(props[at..], 0); + if (text.len > out.len) return error.Invalid; + @memcpy(out[0..text.len], text); + return out[0..text.len]; + } + return error.Invalid; + } +}; diff --git a/zig/src/hip/engine_runtime_tests.zig b/zig/src/hip/engine_runtime_tests.zig new file mode 100644 index 00000000000..109d1d52b86 --- /dev/null +++ b/zig/src/hip/engine_runtime_tests.zig @@ -0,0 +1,52 @@ +//! The runtime pieces an engine uses beyond the model-free tests: device count, free memory, addresses, raw copies. +const std = @import("std"); +const Runtime = @import("runtime.zig").Runtime; +const Context = @import("context.zig").Context; +const Stream = @import("stream.zig").Stream; +const DeviceBuffer = @import("memory.zig").DeviceBuffer; +const HostBuffer = @import("memory.zig").HostBuffer; +const raw = @import("raw.zig"); +const counting = @import("launches/util.zig").counting; + +test "device count and free memory, buffer addresses, pinned views and raw-stream copies and fills" { + var r = try Runtime.open(); + defer r.close(); + try std.testing.expect(try r.deviceCount() >= 1); + var ctx = try Context.init(&r, 0); + defer ctx.deinit(); + const mem = try ctx.memInfo(); + try std.testing.expect(mem.total > 0 and mem.free <= mem.total); + var stream = try Stream.init(&r); + defer stream.deinit(); + const n = 4096; + var a = try DeviceBuffer.alloc(&r, n); + defer a.free(); + var b = try DeviceBuffer.alloc(&r, n); + defer b.free(); + try std.testing.expectEqual(@intFromPtr(a.ptr), a.base()); + var host = try HostBuffer.alloc(&r, 2 * n); + defer host.free(); + for (host.slice(u32), 0..) |*w, i| w.* = @intCast(i); + try std.testing.expectEqual(@as(usize, 2 * n / 4), host.slice(u32).len); + // a view of the second half goes up through the #463 API, comes back through a raw-stream download + try a.uploadAsync(0, host.view(n, 2 * n), stream); + try raw.copy(b, 16, a.base() + 32, n - 32, stream.handle); + try raw.fill8(a, 0xab, stream.handle); + try raw.download(b, 0, host.bytes[0..n], stream.handle); + try stream.synchronize(); + const words = host.slice(u32); + for (words[4 .. n / 4 - 4], n / 4 + 8..) |w, want| try std.testing.expectEqual(@as(u32, @intCast(want)), w); + var back: [n]u8 = undefined; + try a.download(0, &back); + for (back) |x| try std.testing.expectEqual(@as(u8, 0xab), x); + try raw.fill32(a, 0x01020304, stream.handle); + try raw.upload(b, 0, host.bytes[n .. n + 8], stream.handle); + // the counting stream queues nothing + try raw.fill8(a, 0, counting); + try raw.copy(a, 0, b.base(), n, counting); + try stream.synchronize(); + try a.download(0, &back); + for (std.mem.bytesAsSlice(u32, &back)) |w| try std.testing.expectEqual(@as(u32, 0x01020304), w); + try std.testing.expectError(error.Invalid, raw.copy(a, n - 4, b.base(), 8, stream.handle)); + try std.testing.expectError(error.Invalid, raw.upload(a, n, host.bytes[0..1], stream.handle)); +} diff --git a/zig/src/hip/kernel_tests.zig b/zig/src/hip/kernel_tests.zig new file mode 100644 index 00000000000..94641edc08e --- /dev/null +++ b/zig/src/hip/kernel_tests.zig @@ -0,0 +1,29 @@ +//! The model-free kernels on a real GPU: every kernel resolves, and each launch matches its host reference. +const std = @import("std"); +const Runtime = @import("runtime.zig").Runtime; +const Context = @import("context.zig").Context; +const kernels = @import("kernels.zig"); +const Launcher = @import("launches.zig").Launcher; + +test "the code objects load on this device and every kernel the launchers use resolves" { + var r = try Runtime.open(); + defer r.close(); + var ctx = try Context.init(&r, 0); + defer ctx.deinit(); + var arch_buffer: [256]u8 = undefined; + const arch = try @import("device_arch.zig").query(&r, 0, &arch_buffer); + try std.testing.expectEqualStrings(kernels.arch, arch); + var l = try Launcher.load(&r, .{}, kernels.images); + defer l.unload(); +} + +test { + _ = @import("kernel_tests/gdn.zig"); + _ = @import("kernel_tests/decode.zig"); + _ = @import("kernel_tests/chain.zig"); + _ = @import("kernel_tests/attention.zig"); + _ = @import("kernel_tests/ops.zig"); + _ = @import("kernel_tests/tp.zig"); + _ = @import("kernel_tests/affine/affine.zig"); + _ = @import("kernel_tests/affine/rows.zig"); +} diff --git a/zig/src/hip/kernel_tests/affine/affine.zig b/zig/src/hip/kernel_tests/affine/affine.zig new file mode 100644 index 00000000000..605ba017e5a --- /dev/null +++ b/zig/src/hip/kernel_tests/affine/affine.zig @@ -0,0 +1,186 @@ +//! Every registered affine entry the GPU has and the shape fits, against float64; rival entries must write equal bytes. + +const std = @import("std"); +const base = @import("../rig.zig"); +const affine = @import("../../launches/affine.zig"); +const registry = @import("core").registry; +const runtime = @import("../../runtime.zig"); +const Buffer = base.Buffer; +const gpa = base.gpa; +const data = @import("data.zig"); +const cases = @import("cases.zig"); +const prod = @import("product.zig"); +const Product = prod.Product; +const Rig = prod.Rig; +const Entry = affine.Entry; +const Case = cases.Case; + +/// The largest |y - ref| over the sum of the terms' magnitudes an fp32 sum may have: a few units of rounding a term. +fn bound(k: usize) f64 { + return 0x1p-24 * (8 + 2 * @sqrt(@as(f64, @floatFromInt(k)))); +} + +/// What rounding the output to the activation type may add, relative to the value. +fn roundBound(fp16: bool) f64 { + return if (fp16) 0x1p-10 else 0x1p-8; +} + +const pick = 16; + +/// Evenly spaced indices below `n`, ending on the last one: the edges are sampled too. +fn at(i: usize, count: usize, n: usize) usize { + return if (count <= 1 or n <= count) @min(i, n - 1) else i * (n - 1) / (count - 1); +} + +pub const Totals = struct { products: usize = 0, launches: usize = 0, worst: f64 = 0 }; + +const Ref = struct { row: usize, col: usize, v: @import("reference.zig").Value }; + +/// Largest error of the sampled outputs of `out`, over the bound that holds it. +fn worstOf(p: *const Product, out: Buffer, rounded: bool, refs: []const Ref) !f64 { + var worst: f64 = 0; + const lim = bound(p.c.k); + for (refs) |r| { + var y: f64 = undefined; + const at_ = (r.row * p.c.n + r.col); + if (rounded) { + var b: u16 = 0; + try out.download(at_ * 2, std.mem.asBytes(&b)); + if (p.rig.fp16) { + const h: f16 = @bitCast(b); + y = h; + } else { + y = @as(f32, @bitCast(@as(u32, b) << 16)); + } + // the activation type's own rounding, and the fp32 sum below it + const allowed = roundBound(p.rig.fp16) * @abs(r.v.y) + lim * r.v.norm + 1e-7; + worst = @max(worst, @abs(y - r.v.y) / allowed); + } else { + var f: f32 = 0; + try out.download(at_ * 4, std.mem.asBytes(&f)); + worst = @max(worst, @abs(@as(f64, f) - r.v.y) / (lim * @max(r.v.norm, 1e-30))); + } + } + return worst; +} + +const Seen = struct { e: *const Entry, digest: u64 }; + +fn name(buf: []u8, c: Case, rows: usize) []const u8 { + return std.fmt.bufPrint(buf, "{s} m{d} n{d} k{d} b{d} g{d}", .{ c.name, rows, c.n, c.k, c.bits, c.group }) catch "?"; +} + +/// One product: every entry that takes it, against the reference, and the pickable ones against each other. +pub fn product(rig: *Rig, c: Case, tot: *Totals) !void { + var p = try Product.init(rig, c); + defer p.deinit(); + var label_buf: [160]u8 = undefined; + const label = name(&label_buf, c, p.out_rows); + + var refs: [pick * pick]Ref = undefined; + var n_refs: usize = 0; + for (0..@min(pick, p.out_rows)) |i| for (0..@min(pick, c.n)) |j| { + const row = at(i, pick, p.out_rows); + const col = at(j, pick, c.n); + refs[n_refs] = .{ .row = row, .col = col, .v = p.reference(row, col) }; + n_refs += 1; + }; + + const env = rig.kernels.env(); + var pickable_set: std.ArrayList(*const Entry) = .empty; + defer pickable_set.deinit(gpa); + try prod.pickable(rig.kernels, p.arg(0, 0), p.items, c.path, env, &pickable_set, gpa); + + var out = try Buffer.alloc(rig.base, p.outBytes(false)); + defer out.free(); + // a split entry keeps a dot and a sum of x per group + var partial = try Buffer.alloc(rig.base, if (c.path == .decode and !c.routed()) (c.k / c.group) * p.out_rows * c.n * 8 else 8); + defer partial.free(); + var seen: [2][registry.max_entries]Seen = undefined; + var n_seen: [2]usize = .{ 0, 0 }; + var ran: usize = 0; + for (rig.kernels.reg.entries) |*e| { + if (!prod.takes(&p, e)) continue; + const shape = prod.shapeOf(&p, e); + for ([_]bool{ false, true }) |rounded| { + if (rounded and (!e.roundsAct(shape) or e.family == .split or c.routed())) continue; + try out.fill8(0xA5, null); + try prod.launchEntry(&p, e, out, rounded, partial.ptr, 0); + try rig.base.stream.synchronize(); + const worst = try worstOf(&p, out, rounded, refs[0..n_refs]); + tot.worst = @max(tot.worst, worst); + try base.expect(worst <= 1, "affine {s}: {s}{s} is {d:.1} times the error an fp32 sum may have against float64", .{ label, e.id, if (rounded) " (rounded)" else "", worst }); + const digest = try prod.digestOf(out, p.outBytes(rounded)); + rig.digest = std.hash.Wyhash.hash(rig.digest, std.mem.asBytes(&digest)); + const r: usize = @intFromBool(rounded); + if (std.mem.indexOfScalar(*const Entry, pickable_set.items, e) != null) { + seen[r][n_seen[r]] = .{ .e = e, .digest = digest }; + n_seen[r] += 1; + } + ran += 1; + } + } + try base.expect(ran > 0, "affine {s}: no registered entry takes the product", .{label}); + // entries the registry picks between by rows write one set of bytes; the rows group checks routed decode plans + if (env.stream_on and env.gemm_on and !(c.routed() and c.path == .decode)) for (seen, n_seen) |picked, n| { + if (n < 2) continue; + for (picked[1..n]) |s| try base.expect(s.digest == picked[0].digest, "affine {s}: {s} writes other bytes than {s}, which the registry picks between by rows", .{ label, s.e.id, picked[0].e.id }); + }; + tot.products += 1; + tot.launches += ran; +} + +/// A table of products: the decode or prefill shapes. +pub fn list(rig: *Rig, table: []const Case) !void { + var tot: Totals = .{}; + for (table) |c| try product(rig, c, &tot); +} + +fn ragged(comptime path: registry.Path) [6 * 3 * 4 * 3 + 6]Case { + var out: [6 * 3 * 4 * 3 + 6]Case = undefined; + var i: usize = 0; + const rows = if (path == .prefill) [_]usize{ 64, 100, 129, 300 } else [_]usize{ 1, 3, 8, 16 }; + const cols = [_]usize{ 1, 33, 130, 257 }; + for (cases.widths) |bits| for (cases.groups) |group| for (rows, 0..) |m, r| { + // k in groups: one, an odd stage count of 32-code stages (group 32 only) and a few + const ks = [_]usize{ group, group * 3, if (group == 32) 2080 else 4 * @as(usize, group) }; + for (ks, 0..) |k, j| { + out[i] = .{ .name = "ragged", .path = path, .rows = m, .n = cols[(r + j) % cols.len], .k = k, .bits = bits, .group = group }; + i += 1; + } + }; + // routed: short items over a few experts + for (cases.widths) |bits| { + out[i] = .{ .name = "ragged routed", .path = path, .rows = 300, .n = 200, .k = 256, .bits = bits, .experts = 40, .slots = 2, .item_rows = if (path == .prefill) 128 else 8 }; + i += 1; + } + return out; +} + +/// Every width and group on ragged sizes, odd stage counts and short routed items, on both paths. +pub fn sweep(rig: *Rig) !void { + var tot: Totals = .{}; + for (ragged(.prefill)) |c| try product(rig, c, &tot); + for (ragged(.decode)) |c| try product(rig, c, &tot); +} + +test "every affine entry on the served decode shapes sits within an fp32 sum of float64; picked entries write equal bytes" { + const b = try base.Rig.open(1 << 20); + defer b.close(); + var rig = Rig.open(b); + try list(&rig, &cases.decode); +} + +test "every affine entry on the served prompt shapes sits within an fp32 sum of float64; picked entries write equal bytes" { + const b = try base.Rig.open(1 << 20); + defer b.close(); + var rig = Rig.open(b); + try list(&rig, &cases.prefill); +} + +test "every width and group on ragged sizes, odd stage counts and short routed items, on both paths" { + const b = try base.Rig.open(1 << 20); + defer b.close(); + var rig = Rig.open(b); + try sweep(&rig); +} diff --git a/zig/src/hip/kernel_tests/affine/cases.zig b/zig/src/hip/kernel_tests/affine/cases.zig new file mode 100644 index 00000000000..7d4a42222fa --- /dev/null +++ b/zig/src/hip/kernel_tests/affine/cases.zig @@ -0,0 +1,120 @@ +//! The products the affine groups run every registered kernel on: the served models' projections and ragged sizes. + +const registry = @import("core").registry; + +/// A dense product of `rows` rows of x, or a routed one: `rows` tokens of `slots` experts each over stacked tables. +pub const Case = struct { + name: []const u8, + path: registry.Path = .decode, + rows: usize = 1, + n: usize, + k: usize, + bits: u8 = 4, + group: u16 = 64, + experts: usize = 0, + slots: usize = 9, + /// The routed down product: x has a row a pair, else a row a token. + down: bool = false, + /// The most rows an item of the plan holds. + item_rows: usize = 8, + /// Every expert takes the same number of pairs. + even: bool = false, + + pub fn routed(c: Case) bool { + return c.experts > 0; + } +}; + +/// Decode: a lane round's few rows, dense and routed, on the engine's shapes, reaching every decode tile. +pub const decode = [_]Case{ + .{ .name = "35b lm_head", .n = 248320, .k = 2048 }, + .{ .name = "35b qkv", .n = 8192, .k = 2048 }, + .{ .name = "35b o", .n = 2048, .k = 4096 }, + .{ .name = "35b shared gate_up", .n = 1024, .k = 2048 }, + .{ .name = "35b shared down", .n = 2048, .k = 512 }, + .{ .name = "35b kv", .n = 512, .k = 2048 }, + .{ .name = "35b routed gate_up", .n = 1024, .k = 2048, .experts = 256 }, + .{ .name = "35b routed down", .n = 2048, .k = 512, .experts = 256, .down = true }, + .{ .name = "9b qkv", .n = 8192, .k = 4096 }, + .{ .name = "9b gate_up", .n = 24576, .k = 4096 }, + .{ .name = "9b down", .n = 4096, .k = 12288 }, + .{ .name = "9b lm_head", .n = 248320, .k = 4096 }, + .{ .name = "9b down 6-bit", .n = 4096, .k = 12288, .bits = 6 }, + .{ .name = "9b down 8-bit", .n = 4096, .k = 12288, .bits = 8 }, + .{ .name = "9b gate_up 6-bit", .n = 24576, .k = 4096, .bits = 6 }, + .{ .name = "9b gate_up 8-bit", .n = 24576, .k = 4096, .bits = 8 }, + .{ .name = "9b8 qkv", .n = 12352, .k = 4096, .bits = 8 }, + .{ .name = "9b8 o", .n = 4096, .k = 4096, .bits = 8 }, + .{ .name = "9b8 lm_head", .n = 248320, .k = 4096, .bits = 8 }, + .{ .name = "9b8 kv", .n = 1024, .k = 4096, .bits = 8 }, + .{ .name = "2-bit", .n = 8192, .k = 2048, .bits = 2 }, + .{ .name = "3-bit", .n = 8192, .k = 2048, .bits = 3 }, + .{ .name = "5-bit", .n = 8192, .k = 2048, .bits = 5 }, + .{ .name = "group 32", .n = 8192, .k = 2048, .group = 32 }, + .{ .name = "group 128", .n = 8192, .k = 2048, .group = 128 }, + .{ .name = "ragged", .n = 1001, .k = 2112 }, + .{ .name = "stride k4032", .n = 24576, .k = 4032 }, + .{ .name = "stride k4160", .n = 24576, .k = 4160 }, + .{ .name = "stride k2048", .n = 49152, .k = 2048 }, + .{ .name = "stride k8192", .n = 12288, .k = 8192 }, + .{ .name = "35b qkv x2", .rows = 2, .n = 8192, .k = 2048 }, + .{ .name = "35b qkv x4", .rows = 4, .n = 8192, .k = 2048 }, + .{ .name = "35b qkv x8", .rows = 8, .n = 8192, .k = 2048 }, + .{ .name = "35b qkv x16", .rows = 16, .n = 8192, .k = 2048 }, + .{ .name = "9b gate_up x4", .rows = 4, .n = 24576, .k = 4096 }, + .{ .name = "9b gate_up x8", .rows = 8, .n = 24576, .k = 4096 }, + .{ .name = "9b gate_up x12", .rows = 12, .n = 24576, .k = 4096 }, + .{ .name = "9b gate_up x16", .rows = 16, .n = 24576, .k = 4096 }, + .{ .name = "35b routed gate_up x2", .rows = 2, .n = 1024, .k = 2048, .experts = 256 }, + .{ .name = "35b routed gate_up x4", .rows = 4, .n = 1024, .k = 2048, .experts = 256 }, + .{ .name = "35b routed gate_up x8", .rows = 8, .n = 1024, .k = 2048, .experts = 256 }, + .{ .name = "35b routed down x4", .rows = 4, .n = 2048, .k = 512, .experts = 256, .down = true }, +}; + +// Prefill: a prompt's rows. The routed rows are tokens, 8 experts each over 256, in items of at most 128 rows. +pub const prefill = [_]Case{ + .{ .name = "35b qkv", .path = .prefill, .rows = 2048, .n = 8192, .k = 2048 }, + .{ .name = "35b qkv", .path = .prefill, .rows = 8192, .n = 8192, .k = 2048 }, + .{ .name = "35b o", .path = .prefill, .rows = 2048, .n = 2048, .k = 4096 }, + .{ .name = "35b o", .path = .prefill, .rows = 8192, .n = 2048, .k = 4096 }, + .{ .name = "35b shared gate_up", .path = .prefill, .rows = 8192, .n = 1024, .k = 2048 }, + .{ .name = "35b expert gate_up", .path = .prefill, .rows = 64, .n = 1024, .k = 2048 }, + .{ .name = "35b expert gate_up", .path = .prefill, .rows = 256, .n = 1024, .k = 2048 }, + .{ .name = "35b expert down", .path = .prefill, .rows = 256, .n = 2048, .k = 512 }, + .{ .name = "35b routed gate_up", .path = .prefill, .rows = 2048, .n = 1024, .k = 2048, .experts = 256, .slots = 8, .item_rows = 128 }, + .{ .name = "35b routed gate_up", .path = .prefill, .rows = 8192, .n = 1024, .k = 2048, .experts = 256, .slots = 8, .item_rows = 128 }, + .{ .name = "35b routed even 32", .path = .prefill, .rows = 1024, .n = 1024, .k = 2048, .experts = 256, .slots = 8, .item_rows = 128, .even = true }, + .{ .name = "35b routed even 64", .path = .prefill, .rows = 2048, .n = 1024, .k = 2048, .experts = 256, .slots = 8, .item_rows = 128, .even = true }, + .{ .name = "35b routed down", .path = .prefill, .rows = 2048, .n = 2048, .k = 512, .experts = 256, .slots = 8, .item_rows = 128, .down = true }, + .{ .name = "35b routed down", .path = .prefill, .rows = 8192, .n = 2048, .k = 512, .experts = 256, .slots = 8, .item_rows = 128, .down = true }, + .{ .name = "9b qkv", .path = .prefill, .rows = 2048, .n = 8192, .k = 4096 }, + .{ .name = "9b gate_up", .path = .prefill, .rows = 2048, .n = 24576, .k = 4096 }, + .{ .name = "9b gate_up", .path = .prefill, .rows = 8192, .n = 12288, .k = 4096 }, + .{ .name = "9b down", .path = .prefill, .rows = 2048, .n = 4096, .k = 12288 }, + .{ .name = "9b down", .path = .prefill, .rows = 8192, .n = 4096, .k = 12288 }, + .{ .name = "27b gate_up", .path = .prefill, .rows = 2048, .n = 17408, .k = 5120 }, + .{ .name = "27b down", .path = .prefill, .rows = 2048, .n = 5120, .k = 17408 }, + .{ .name = "27b q", .path = .prefill, .rows = 8192, .n = 12288, .k = 5120 }, + .{ .name = "vocab", .path = .prefill, .rows = 128, .n = 248320, .k = 2048 }, + .{ .name = "3-bit", .path = .prefill, .rows = 2048, .n = 4096, .k = 2048, .bits = 3 }, + .{ .name = "6-bit", .path = .prefill, .rows = 2048, .n = 4096, .k = 2048, .bits = 6 }, + .{ .name = "8-bit", .path = .prefill, .rows = 2048, .n = 4096, .k = 2048, .bits = 8 }, + .{ .name = "group 32", .path = .prefill, .rows = 2048, .n = 4096, .k = 2048, .group = 32 }, + .{ .name = "group 128", .path = .prefill, .rows = 2048, .n = 4096, .k = 2048, .group = 128 }, + .{ .name = "edges", .path = .prefill, .rows = 1000, .n = 1001, .k = 2112 }, +}; + +pub const widths = [_]u8{ 2, 3, 4, 5, 6, 8 }; +pub const groups = [_]u16{ 32, 64, 128 }; + +/// A short prompt's few rows, for the timings of each tile on dense and routed products. +pub const short_rows = [_]usize{ 1, 2, 4, 8, 13, 24, 32, 64 }; +pub const short_tokens = [_]usize{ 1, 13, 32, 64, 128, 256 }; +pub const short = [_]Case{ + .{ .name = "9b qkv", .path = .prefill, .n = 8192, .k = 4096 }, + .{ .name = "9b gate_up", .path = .prefill, .n = 24576, .k = 4096 }, + .{ .name = "9b down", .path = .prefill, .n = 4096, .k = 12288 }, + .{ .name = "35b o", .path = .prefill, .n = 2048, .k = 4096 }, + .{ .name = "35b routed gate_up", .path = .prefill, .n = 1024, .k = 2048, .experts = 256, .slots = 8, .item_rows = 128 }, + .{ .name = "35b routed down", .path = .prefill, .n = 2048, .k = 512, .experts = 256, .slots = 8, .item_rows = 128, .down = true }, +}; diff --git a/zig/src/hip/kernel_tests/affine/data.zig b/zig/src/hip/kernel_tests/affine/data.zig new file mode 100644 index 00000000000..3336885c94e --- /dev/null +++ b/zig/src/hip/kernel_tests/affine/data.zig @@ -0,0 +1,89 @@ +//! Random packed products and the device compare the affine tests share. + +const std = @import("std"); +const base = @import("../rig.zig"); +const affine = @import("../../launches/affine.zig"); +const registry = @import("core").registry; +const runtime = @import("../../runtime.zig"); +const Buffer = base.Buffer; +const gpa = base.gpa; + +pub const Rng = struct { + state: u64, + + pub fn next(r: *Rng) u64 { + r.state ^= r.state >> 12; + r.state ^= r.state << 25; + r.state ^= r.state >> 27; + return r.state *% 0x2545F4914F6CDD1D; + } + + /// A value in [-1, 1) with a few mantissa bits, so activation sums stay far from overflow. + pub fn unit(r: *Rng) f32 { + const v: i32 = @intCast(r.next() >> 40 & 0x7ff); + return @as(f32, @floatFromInt(v - 1024)) / 1024.0; + } +}; + +pub fn bf16Bits(v: f32) u16 { + return @intCast(@as(u32, @bitCast(v)) >> 16); +} + +pub fn f16Bits(v: f32) u16 { + const h: f16 = @floatCast(v); + return @bitCast(h); +} + +pub fn fill(_: std.mem.Allocator, comptime T: type, n: usize, rng: *Rng, make: *const fn (*Rng) T) ![]T { + const host = try gpa.alloc(T, n); + for (host) |*v| v.* = make(rng); + return host; +} + +pub fn makeWord(r: *Rng) u32 { + return @truncate(r.next() >> 16); +} + +pub fn makeScale(r: *Rng) u16 { + return bf16Bits((r.unit() + 1.0) / 16.0); +} + +pub fn makeBias(r: *Rng) u16 { + return bf16Bits(r.unit() / 2.0); +} + +/// A full-mantissa activation in [-1, 1) at one of six scales: sums of products then round, in any order. +pub fn fine(r: *Rng) f32 { + const v = r.next(); + const m: i32 = @intCast(v >> 41 & 0x3fffff); + return @as(f32, @floatFromInt(m - 0x200000)) / 2097152.0 * std.math.ldexp(@as(f32, 1), -@as(i32, @intCast(v % 6))); +} + +pub fn makeX16(r: *Rng) u16 { + return f16Bits(fine(r)); +} + +pub fn makeXB(r: *Rng) u16 { + return bf16Bits(fine(r)); +} + +/// Words of two device buffers that differ, compared through 32 MiB windows. +pub fn sameOnDevice(a: Buffer, b: Buffer, len: usize) !usize { + const win = 32 << 20; + const ha = try gpa.alloc(u8, win); + defer gpa.free(ha); + const hb = try gpa.alloc(u8, win); + defer gpa.free(hb); + var diff: usize = 0; + var at: usize = 0; + while (at < len) : (at += win) { + const n = @min(win, len - at); + try a.download(at, ha[0..n]); + try b.download(at, hb[0..n]); + var i: usize = 0; + while (i + 4 <= n) : (i += 4) { + if (!std.mem.eql(u8, ha[i..][0..4], hb[i..][0..4])) diff += 1; + } + } + return diff; +} diff --git a/zig/src/hip/kernel_tests/affine/product.zig b/zig/src/hip/kernel_tests/affine/product.zig new file mode 100644 index 00000000000..20385757477 --- /dev/null +++ b/zig/src/hip/kernel_tests/affine/product.zig @@ -0,0 +1,261 @@ +//! One random packed affine product on the host and the device, launched by any registry entry, with its reference. + +const std = @import("std"); +const base = @import("../rig.zig"); +const affine = @import("../../launches/affine.zig"); +const registry = @import("core").registry; +const runtime = @import("../../runtime.zig"); +const Buffer = base.Buffer; +const gpa = base.gpa; +const data = @import("data.zig"); +const ref = @import("reference.zig"); +const cases = @import("cases.zig"); +const Kernels = affine.Kernels; +const Entry = affine.Entry; + +/// The device a group runs on: the shared rig, the registry's kernels and the seeded generator. +pub const Rig = struct { + base: *base.Rig, + kernels: *const Kernels, + fp16: bool, + rng: data.Rng = .{ .state = 0x9E3779B97F4A7C15 }, + /// A running hash of the bytes every launch wrote: the same before and after a change that keeps its bits. + digest: u64 = 0, + + pub fn open(b: *base.Rig) Rig { + return .{ .base = b, .kernels = &b.on.affine, .fp16 = !b.bf16 }; + } +}; + +pub const Product = struct { + rig: *Rig, + c: cases.Case, + hx: []u16, + hw: []u32, + hs: []u16, + hb: []u16, + expert_of: []u32 = &.{}, + x: Buffer, + words: Buffer, + scale: Buffer, + bias: Buffer, + plan: ?Buffer = null, + members: ?Buffer = null, + /// A plan's items and the most rows in one; the output rows a launch writes. + items: usize = 1, + max_rows: usize, + out_rows: usize, + /// Copies of the tables back to back, so timed launches read weights from DRAM. + copies: usize, + copy_words: usize, + copy_tab: usize, + + pub fn init(rig: *Rig, c: cases.Case) !Product { + const experts = @max(c.experts, 1); + const words_row = c.k * c.bits / 32; + const groups = c.k / c.group; + const pairs = c.rows * c.slots; + var p: Product = undefined; + p.rig = rig; + p.c = c; + p.items = 1; + p.max_rows = c.rows; + p.out_rows = if (c.routed()) pairs else c.rows; + p.plan = null; + p.members = null; + p.expert_of = &.{}; + p.copy_words = std.mem.alignForward(usize, experts * c.n * words_row, 64); + p.copy_tab = std.mem.alignForward(usize, experts * c.n * groups, 128); + const copy_bytes = p.copy_words * 4 + p.copy_tab * 4; + p.copies = 1; + _ = copy_bytes; + const x_rows: usize = if (!c.routed()) c.rows else if (c.down) pairs else c.rows; + p.hx = try data.fill(gpa, u16, x_rows * c.k, &rig.rng, if (rig.fp16) data.makeX16 else data.makeXB); + errdefer gpa.free(p.hx); + p.hw = try data.fill(gpa, u32, p.copy_words, &rig.rng, data.makeWord); + errdefer gpa.free(p.hw); + p.hs = try data.fill(gpa, u16, p.copy_tab, &rig.rng, data.makeScale); + errdefer gpa.free(p.hs); + p.hb = try data.fill(gpa, u16, p.copy_tab, &rig.rng, data.makeBias); + errdefer gpa.free(p.hb); + p.x = try Buffer.fromHost(rig.base, p.hx); + errdefer p.x.free(); + p.words = try Buffer.alloc(rig.base, p.copies * p.copy_words * 4); + errdefer p.words.free(); + p.scale = try Buffer.alloc(rig.base, p.copies * p.copy_tab * 2); + errdefer p.scale.free(); + p.bias = try Buffer.alloc(rig.base, p.copies * p.copy_tab * 2); + errdefer p.bias.free(); + for (0..p.copies) |i| { + try p.words.upload(i * p.copy_words * 4, std.mem.sliceAsBytes(p.hw)); + try p.scale.upload(i * p.copy_tab * 2, std.mem.sliceAsBytes(p.hs)); + try p.bias.upload(i * p.copy_tab * 2, std.mem.sliceAsBytes(p.hb)); + } + if (c.routed()) try p.makePlan(pairs); + return p; + } + + /// Each pair draws an expert; the pairs sorted by expert are cut into items of at most `item_rows`. + fn makePlan(p: *Product, pairs: usize) !void { + const c = p.c; + p.expert_of = try gpa.alloc(u32, pairs); + for (p.expert_of, 0..) |*e, i| e.* = if (c.even) @intCast(i % c.experts) else @intCast(p.rig.rng.next() % c.experts); + const order = try gpa.alloc(i32, pairs); + defer gpa.free(order); + for (order, 0..) |*o, i| o.* = @intCast(i); + std.mem.sort(i32, order, p.expert_of, struct { + fn less(of: []u32, a: i32, b: i32) bool { + const ea = of[@intCast(a)]; + const eb = of[@intCast(b)]; + return if (ea != eb) ea < eb else a < b; + } + }.less); + const items = try gpa.alloc(i32, pairs * 3); + defer gpa.free(items); + var count: usize = 0; + var i: usize = 0; + p.max_rows = 1; + while (i < pairs) { + const e = p.expert_of[@intCast(order[i])]; + var j = i; + while (j < pairs and j - i < c.item_rows and p.expert_of[@intCast(order[j])] == e) j += 1; + items[count * 3 ..][0..3].* = .{ @intCast(e), @intCast(i), @intCast(j - i) }; + p.max_rows = @max(p.max_rows, j - i); + count += 1; + i = j; + } + p.items = count; + p.plan = try Buffer.fromHost(p.rig.base, items[0 .. count * 3]); + p.members = try Buffer.fromHost(p.rig.base, order); + } + + pub fn deinit(p: *Product) void { + gpa.free(p.hx); + gpa.free(p.hw); + gpa.free(p.hs); + gpa.free(p.hb); + gpa.free(p.expert_of); + p.x.free(); + p.words.free(); + p.scale.free(); + p.bias.free(); + if (p.plan) |*b| b.free(); + if (p.members) |*b| b.free(); + } + + pub fn flops(p: Product) f64 { + return 2.0 * @as(f64, @floatFromInt(p.out_rows)) * @as(f64, @floatFromInt(p.c.n)) * @as(f64, @floatFromInt(p.c.k)); + } + + /// The bytes of weights and tables a launch reads (every expert an item names, once). + pub fn bytes(p: Product) f64 { + const per = @as(f64, @floatFromInt(p.c.n)) * @as(f64, @floatFromInt(p.c.k * p.c.bits / 8 + 4 * (p.c.k / p.c.group))); + if (!p.c.routed()) return per; + var seen = std.bit_set.DynamicBitSetUnmanaged.initEmpty(gpa, p.c.experts) catch return per; + defer seen.deinit(gpa); + for (p.expert_of) |e| seen.set(e); + return per * @as(f64, @floatFromInt(seen.count())); + } + + pub fn arg(p: Product, out: u64, copy: usize) affine.Arg { + const c = p.c; + return .{ + .x = p.x.ptr, + .words = p.words.ptr + copy * p.copy_words * 4, + .scale = .{ .p = p.scale.ptr + copy * p.copy_tab * 2, .kind = 1 }, + .bias = .{ .p = p.bias.ptr + copy * p.copy_tab * 2, .kind = 1 }, + .out = out, + .m = @intCast(if (c.routed()) p.max_rows else c.rows), + .n = @intCast(c.n), + .k = @intCast(c.k), + .bits = c.bits, + .group = c.group, + .fp16 = @intFromBool(p.rig.fp16), + .route = if (c.routed()) .{ .items = p.plan.?.ptr, .members = p.members.?.ptr, .x_div = @intCast(if (c.down) 1 else c.slots) } else .{}, + }; + } + + pub fn outBytes(p: Product, rounded: bool) usize { + return p.out_rows * p.c.n * @as(usize, if (rounded) 2 else 4); + } + + pub fn problem(p: *const Product) ref.Problem { + return .{ .fp16 = p.rig.fp16, .n = p.c.n, .k = p.c.k, .bits = p.c.bits, .group = p.c.group, .x = p.hx, .words = p.hw, .scale = p.hs, .bias = p.hb }; + } + + /// The float64 value of output (`row`, `col`). + pub fn reference(p: *const Product, row: usize, col: usize) ref.Value { + if (!p.c.routed()) return ref.reference(p.problem(), row, 0, col); + return ref.reference(p.problem(), if (p.c.down) row else row / p.c.slots, p.expert_of[row], col); + } +}; + +/// The shape a registry entry is asked about: a split entry is asked for two parts. +pub fn shapeFor(a: affine.Arg, items: usize, e: *const Entry) registry.Shape { + var s = Kernels.shapeOf(a, @intCast(items)); + if (e.family == .split) s.parts = 2; + return s; +} + +pub fn shapeOf(p: *const Product, e: *const Entry) registry.Shape { + return shapeFor(p.arg(0, 0), p.items, e); +} + +/// Whether `e` is an entry of the launch's (op, path) that the GPU has and whose shape takes it. +pub fn takesArg(k: *const Kernels, e: *const Entry, a: affine.Arg, items: usize, path: registry.Path) bool { + const op: registry.Op = if (a.route.items != 0) .routed else .project; + if (e.format != .mlx or e.op != op or e.path != path) return false; + var env = k.env(); + env.matrix_on = env.matrix; + return e.caps(env) and e.fits(shapeFor(a, items, e)); +} + +/// Entries of the product's (op, path) that the GPU has and whose shapes take it. +pub fn takes(p: *const Product, e: *const Entry) bool { + return takesArg(p.rig.kernels, e, p.arg(0, 0), p.items, p.c.path); +} + +/// The entries the registry picks between at some row count under `env`, for the shape of `a`. +pub fn pickable(k: *const Kernels, a: affine.Arg, items: usize, path: registry.Path, env: registry.Env, out: *std.ArrayList(*const Entry), alloc: std.mem.Allocator) !void { + const op: registry.Op = if (a.route.items != 0) .routed else .project; + var shape = Kernels.shapeOf(a, @intCast(items)); + // a lane round keeps one family at every row count; outside one the decode tiles change with the rows + shape.round = path == .decode; + for (1..registry.rule_rows + 1) |m| { + shape.m = @intCast(m); + const e = k.reg.select(env, .mlx, op, path, shape) orelse continue; + if (std.mem.indexOfScalar(*const Entry, out.items, e) == null) try out.append(alloc, e); + } +} + +/// Launches `e` on the product into `out`, rounded to the activation type when `rounded`. +pub fn launchEntry(p: *const Product, e: *const Entry, out: Buffer, rounded: bool, partial: u64, copy: usize) runtime.Error!void { + var a = p.arg(out.ptr, copy); + if (rounded) { + a.out16 = a.out; + a.out = 0; + } + try e.launch(p.rig.kernels, .{ + .r = &p.rig.base.r, + .s = p.rig.base.stream.handle, + .arg = a, + .items = @intCast(p.items), + .partial = partial, + .parts = if (e.family == .split) 2 else 1, + }); +} + +/// A hash of a device buffer's first `len` bytes, read through windows. +pub fn digestOf(buf: Buffer, len: usize) !u64 { + const win = 32 << 20; + const host = try gpa.alloc(u8, @min(win, len)); + defer gpa.free(host); + var h: u64 = 0; + var at: usize = 0; + while (at < len) : (at += win) { + const n = @min(win, len - at); + try buf.download(at, host[0..n]); + h = std.hash.Wyhash.hash(h, host[0..n]); + } + return h; +} diff --git a/zig/src/hip/kernel_tests/affine/reference.zig b/zig/src/hip/kernel_tests/affine/reference.zig new file mode 100644 index 00000000000..2b707a3959e --- /dev/null +++ b/zig/src/hip/kernel_tests/affine/reference.zig @@ -0,0 +1,76 @@ +//! A float64 reference for the packed affine product, dequant(W) . x, on sampled outputs, and error statistics. + +const std = @import("std"); + +/// One product on the host: fp16 or bf16 activations, and `experts` back to back of words with bf16 scales and biases. +pub const Problem = struct { + fp16: bool, + n: usize, + k: usize, + bits: usize, + group: usize, + x: []const u16, + words: []const u32, + scale: []const u16, + bias: []const u16, +}; + +fn bf16(b: u16) f64 { + return @as(f32, @bitCast(@as(u32, b) << 16)); +} + +fn activation(p: Problem, b: u16) f64 { + if (!p.fp16) return bf16(b); + const h: f16 = @bitCast(b); + return h; +} + +/// Code `k` of a column's packed row. +fn code(row: []const u32, k: usize, bits: usize) u32 { + const at = k * bits; + const shift: u5 = @intCast(at & 31); + var v: u32 = row[at >> 5] >> shift; + if (@as(usize, shift) + bits > 32) v |= row[(at >> 5) + 1] << @intCast(32 - @as(usize, shift)); + return v & ((@as(u32, 1) << @intCast(bits)) - 1); +} + +pub const Value = struct { y: f64, norm: f64 }; + +/// The product of x row `row` with column `col` of expert `expert`, and the sum of the magnitudes of its terms. +pub fn reference(p: Problem, row: usize, expert: usize, col: usize) Value { + const groups = p.k / p.group; + const words_row = p.k * p.bits / 32; + const col_at = expert * p.n + col; + const w = p.words[col_at * words_row ..][0..words_row]; + var y: f64 = 0; + var norm: f64 = 0; + for (0..p.k) |k| { + const g = k / p.group; + const s = bf16(p.scale[col_at * groups + g]); + const b = bf16(p.bias[col_at * groups + g]); + const term = activation(p, p.x[row * p.k + k]) * (@as(f64, @floatFromInt(code(w, k, p.bits))) * s + b); + y += term; + norm += @abs(term); + } + return .{ .y = y, .norm = norm }; +} + +/// Errors of one kernel's outputs: largest |y - ref| / norm (norm: what the terms could sum to), largest and rms. +pub const Stat = struct { + max_rel: f64 = 0, + max_abs: f64 = 0, + sum_sq: f64 = 0, + count: usize = 0, + + pub fn add(s: *Stat, y: f32, v: Value) void { + const e = @abs(@as(f64, y) - v.y); + s.max_abs = @max(s.max_abs, e); + if (v.norm > 0) s.max_rel = @max(s.max_rel, e / v.norm); + s.sum_sq += e * e; + s.count += 1; + } + + pub fn rms(s: Stat) f64 { + return if (s.count == 0) 0 else @sqrt(s.sum_sq / @as(f64, @floatFromInt(s.count))); + } +}; diff --git a/zig/src/hip/kernel_tests/affine/rows.zig b/zig/src/hip/kernel_tests/affine/rows.zig new file mode 100644 index 00000000000..bd67c6a91bb --- /dev/null +++ b/zig/src/hip/kernel_tests/affine/rows.zig @@ -0,0 +1,420 @@ +//! Rows are the same bytes however a product is cut: decode's lane rounds, prefill's tiles and the router's kernels. + +const std = @import("std"); +const base = @import("../rig.zig"); +const affine = @import("../../launches/affine.zig"); +const registry = @import("core").registry; +const runtime = @import("../../runtime.zig"); +const Buffer = base.Buffer; +const gpa = base.gpa; +const data = @import("data.zig"); +const prod = @import("product.zig"); +const shapes = @import("cases.zig"); +const Rig = prod.Rig; +const Entry = affine.Entry; + +const Case = struct { name: []const u8, n: usize, k: usize, bits: c_int = 4, group: c_int = 64 }; + +const cases = [_]Case{ + .{ .name = "vocab", .n = 248320, .k = 2048 }, + .{ .name = "qkv", .n = 8192, .k = 2048 }, + .{ .name = "down", .n = 2048, .k = 512 }, + .{ .name = "9b gate_up", .n = 24576, .k = 4096 }, + .{ .name = "ragged", .n = 1001, .k = 2112 }, + .{ .name = "2-bit", .n = 4096, .k = 2048, .bits = 2 }, + .{ .name = "3-bit", .n = 4096, .k = 2048, .bits = 3 }, + .{ .name = "5-bit", .n = 4096, .k = 2048, .bits = 5 }, + .{ .name = "6-bit group 32", .n = 4096, .k = 2048, .bits = 6, .group = 32 }, + .{ .name = "8-bit group 128", .n = 4096, .k = 2048, .bits = 8, .group = 128 }, +}; + +/// Row counts launched together: every count of a lane round up to 16, then wider rounds. +const together = [_]usize{ 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 20, 24, 32 }; +const most_rows = 32; + +/// One product at every row count: the number of rows whose bytes differ from the same row alone. +fn product(t: *Rig, rng: *data.Rng, c: Case, half: bool) !usize { + const words_row = c.k * @as(usize, @intCast(c.bits)) / 32; + const groups = c.k / @as(usize, @intCast(c.group)); + const hx = try data.fill(gpa, u16, most_rows * c.k, rng, if (t.fp16) data.makeX16 else data.makeXB); + defer gpa.free(hx); + const hw = try data.fill(gpa, u32, c.n * words_row, rng, data.makeWord); + defer gpa.free(hw); + const hs = try data.fill(gpa, u16, c.n * groups, rng, data.makeScale); + defer gpa.free(hs); + const hb = try data.fill(gpa, u16, c.n * groups, rng, data.makeBias); + defer gpa.free(hb); + var x = try Buffer.fromHost(t.base, hx); + defer x.free(); + var words = try Buffer.fromHost(t.base, hw); + defer words.free(); + var scale = try Buffer.fromHost(t.base, hs); + defer scale.free(); + var bias = try Buffer.fromHost(t.base, hb); + defer bias.free(); + const size: usize = if (half) 2 else 4; + var out = try Buffer.alloc(t.base, most_rows * c.n * size); + defer out.free(); + const alone = try gpa.alloc(u8, most_rows * c.n * size); + defer gpa.free(alone); + const got = try gpa.alloc(u8, most_rows * c.n * size); + defer gpa.free(got); + + var arg: affine.Arg = .{ + .x = x.ptr, + .words = words.ptr, + .scale = .{ .p = scale.ptr, .kind = 1 }, + .bias = .{ .p = bias.ptr, .kind = 1 }, + .out = out.ptr, + .m = 1, + .n = @intCast(c.n), + .k = @intCast(c.k), + .bits = c.bits, + .group = c.group, + .fp16 = @intFromBool(t.fp16), + }; + // each row alone + for (0..most_rows) |i| { + arg.x = x.ptr + i * c.k * 2; + arg.m = 1; + try out.fill8(0xA5, null); + try t.kernels.run(&t.base.r, arg, 4, t.base.stream.handle, 0, 1, half); + try t.base.stream.synchronize(); + try out.download(0, alone[i * c.n * size ..][0 .. c.n * size]); + } + // the rows together + var bad: usize = 0; + arg.x = x.ptr; + for (together) |m| { + arg.m = @intCast(m); + try out.fill8(0xA5, null); + try t.kernels.run(&t.base.r, arg, 4, t.base.stream.handle, 0, 1, half); + try t.base.stream.synchronize(); + try out.download(0, got[0 .. m * c.n * size]); + for (0..m) |i| { + const row = i * c.n * size; + if (!std.mem.eql(u8, got[row..][0 .. c.n * size], alone[row..][0 .. c.n * size])) { + if (bad < 6) std.debug.print(" {s} {s}: row {d} of {d} differs from the row alone\n", .{ c.name, if (half) "rounded" else "fp32", i, m }); + bad += 1; + } + } + } + return bad; +} + +const Plan = struct { counts: [4]c_int }; +const plans = [_]Plan{ .{ .counts = .{ 5, 3, 6, 2 } }, .{ .counts = .{ 15, 9, 1, 4 } }, .{ .counts = .{ 2, 2, 2, 2 } }, .{ .counts = .{ 1, 4, 1, 3 } } }; +const routed_cases = [_]Case{ + .{ .name = "moe gate_up", .n = 1024, .k = 2048 }, + .{ .name = "moe down", .n = 2048, .k = 512 }, + .{ .name = "ragged", .n = 1002, .k = 2112 }, + .{ .name = "3-bit", .n = 1024, .k = 2048, .bits = 3 }, + .{ .name = "8-bit", .n = 1024, .k = 2048, .bits = 8, .group = 128 }, +}; + +fn launchRouted(t: *Rig, arg: affine.Arg, items: c_int, pair: bool) !void { + if (pair) { + if (!try t.kernels.pairRun(&t.base.r, arg, 0, items, t.base.stream.handle)) return error.NoTile; + } else { + try t.kernels.routed(&t.base.r, arg, items, t.base.stream.handle); + } + try t.base.stream.synchronize(); +} + +/// A routed plan's pairs together, against every pair as an item of its own: the number of output rows that differ. +fn routedProduct(t: *Rig, rng: *data.Rng, c: Case, pair: bool) !usize { + const experts = 4; + const words_row = c.k * @as(usize, @intCast(c.bits)) / 32; + const groups = c.k / @as(usize, @intCast(c.group)); + const hx = try data.fill(gpa, u16, 32 * c.k, rng, if (t.fp16) data.makeX16 else data.makeXB); + defer gpa.free(hx); + const hw = try data.fill(gpa, u32, experts * c.n * words_row, rng, data.makeWord); + defer gpa.free(hw); + const hs = try data.fill(gpa, u16, experts * c.n * groups, rng, data.makeScale); + defer gpa.free(hs); + const hb = try data.fill(gpa, u16, experts * c.n * groups, rng, data.makeBias); + defer gpa.free(hb); + var x = try Buffer.fromHost(t.base, hx); + defer x.free(); + var words = try Buffer.fromHost(t.base, hw); + defer words.free(); + var scale = try Buffer.fromHost(t.base, hs); + defer scale.free(); + var bias = try Buffer.fromHost(t.base, hb); + defer bias.free(); + const cols = if (pair) c.n / 2 else c.n; + const size: usize = if (pair) 2 else 4; + var out = try Buffer.alloc(t.base, 32 * cols * size); + defer out.free(); + const alone = try gpa.alloc(u8, 32 * cols * size); + defer gpa.free(alone); + const got = try gpa.alloc(u8, 32 * cols * size); + defer gpa.free(got); + var members: [32]c_int = undefined; + for (&members, 0..) |*mb, i| mb.* = @intCast(i); + var mem = try Buffer.fromHost(t.base, @as([]const c_int, &members)); + defer mem.free(); + + var bad: usize = 0; + for (plans) |plan| { + var rows: usize = 0; + var item_alone: [96]c_int = undefined; + var item_all: [12]c_int = undefined; + var most: c_int = 0; + for (plan.counts, 0..) |n, e| { + item_all[3 * e] = @intCast(e); + item_all[3 * e + 1] = @intCast(rows); + item_all[3 * e + 2] = n; + most = @max(most, n); + for (0..@as(usize, @intCast(n))) |_| { + item_alone[3 * rows] = @intCast(e); + item_alone[3 * rows + 1] = @intCast(rows); + item_alone[3 * rows + 2] = 1; + rows += 1; + } + } + var plan_alone = try Buffer.fromHost(t.base, @as([]const c_int, item_alone[0 .. 3 * rows])); + defer plan_alone.free(); + var plan_all = try Buffer.fromHost(t.base, @as([]const c_int, &item_all)); + defer plan_all.free(); + var arg: affine.Arg = .{ + .x = x.ptr, + .words = words.ptr, + .scale = .{ .p = scale.ptr, .kind = 1 }, + .bias = .{ .p = bias.ptr, .kind = 1 }, + .out = if (pair) 0 else out.ptr, + .out16 = if (pair) out.ptr else 0, + .m = 1, + .n = @intCast(c.n), + .k = @intCast(c.k), + .bits = c.bits, + .group = c.group, + .fp16 = @intFromBool(t.fp16), + .route = .{ .items = plan_alone.ptr, .members = mem.ptr, .x_div = 1 }, + }; + try out.fill8(0xA5, null); + try launchRouted(t, arg, @intCast(rows), pair); + try out.download(0, alone[0 .. rows * cols * size]); + arg.m = most; + arg.route.items = plan_all.ptr; + try out.fill8(0xA5, null); + try launchRouted(t, arg, 4, pair); + try out.download(0, got[0 .. rows * cols * size]); + for (0..rows) |i| { + const row = i * cols * size; + if (!std.mem.eql(u8, got[row..][0 .. cols * size], alone[row..][0 .. cols * size])) { + if (bad < 6) std.debug.print(" routed {s} {s}: pair {d} of {d} (most {d} rows) differs from the pair alone\n", .{ c.name, if (pair) "act" else "fp32", i, rows, most }); + bad += 1; + } + } + } + return bad; +} + +/// Row counts the block shapes are compared at: every short one's edges, ragged ones and a few blocks. +const tier_rows = [_]usize{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 31, 33, 63, 64, 65, 100, 128, 200 }; + +/// One product (dense, or routed with ragged and empty items) through every block shape: words unlike the 128-row's. +fn tierProduct(t: *Rig, m: usize, n: usize, k: usize, bits: c_int, group: c_int, routed: bool) !usize { + const experts: usize = if (routed) 5 else 1; + const words_row = k * @as(usize, @intCast(bits)) / 32; + const groups = k / @as(usize, @intCast(group)); + var items: [3 * 256]i32 = undefined; + var item_count: usize = 1; + var max_rows = m; + if (routed) { + item_count = 0; + max_rows = 1; + var first: usize = 0; + while (first < m) { + const take = @min(m - first, 1 + t.rng.next() % 40); + items[item_count * 3 ..][0..3].* = .{ @intCast(item_count % experts), @intCast(first), @intCast(take) }; + item_count += 1; + first += take; + max_rows = @max(max_rows, take); + } + items[item_count * 3 ..][0..3].* = .{ 0, @intCast(m), 0 }; + item_count += 1; + } + const pairs = try gpa.alloc(i32, m); + defer gpa.free(pairs); + for (pairs, 0..) |*p, i| p.* = @intCast(i); + const x_div: usize = if (routed) 2 else 1; + const hx = try data.fill(gpa, u16, (m / x_div + 1) * k, &t.rng, if (t.fp16) data.makeX16 else data.makeXB); + defer gpa.free(hx); + const hw = try data.fill(gpa, u32, experts * n * words_row, &t.rng, data.makeWord); + defer gpa.free(hw); + const hs = try data.fill(gpa, u16, experts * n * groups, &t.rng, data.makeScale); + defer gpa.free(hs); + const hb = try data.fill(gpa, u16, experts * n * groups, &t.rng, data.makeBias); + defer gpa.free(hb); + var x = try Buffer.fromHost(t.base, hx); + defer x.free(); + var words = try Buffer.fromHost(t.base, hw); + defer words.free(); + var scale = try Buffer.fromHost(t.base, hs); + defer scale.free(); + var bias = try Buffer.fromHost(t.base, hb); + defer bias.free(); + var plan = try Buffer.fromHost(t.base, items[0 .. item_count * 3]); + defer plan.free(); + var members = try Buffer.fromHost(t.base, pairs); + defer members.free(); + const bytes = m * n * 4; + var arg: affine.Arg = .{ + .x = x.ptr, + .words = words.ptr, + .scale = .{ .p = scale.ptr, .kind = 1 }, + .bias = .{ .p = bias.ptr, .kind = 1 }, + .out = 0, + .m = @intCast(max_rows), + .n = @intCast(n), + .k = @intCast(k), + .bits = bits, + .group = group, + .fp16 = @intFromBool(t.fp16), + .route = if (routed) .{ .items = plan.ptr, .members = members.ptr, .x_div = @intCast(x_div) } else .{}, + }; + // every tile the registry picks between by rows at this shape, twice, and the engine's own pick + const k_ptr = t.kernels; + var set: std.ArrayList(*const Entry) = .empty; + defer set.deinit(gpa); + try prod.pickable(k_ptr, arg, item_count, .prefill, k_ptr.env(), &set, gpa); + var ids: [registry.max_entries]*const Entry = undefined; + var n_ids: usize = 0; + for (set.items) |e| if (prod.takesArg(k_ptr, e, arg, item_count, .prefill)) { + ids[n_ids] = e; + n_ids += 1; + }; + if (n_ids == 0) return error.NoTile; + const big = n_ids - 1; + var outs: [2 * registry.max_entries + 1]Buffer = undefined; + const n_outs = 2 * n_ids + 1; + for (outs[0..n_outs], 0..) |*o, i| { + o.* = try Buffer.alloc(t.base, bytes); + errdefer for (outs[0..i]) |*f| f.free(); + try o.fill8(0xA5, null); + } + defer for (outs[0..n_outs]) |*o| o.free(); + for (0..2 * n_ids) |i| { + arg.out = outs[i].ptr; + try ids[i % n_ids].launch(k_ptr, .{ .r = &t.base.r, .s = t.base.stream.handle, .arg = arg, .items = @intCast(item_count) }); + } + arg.out = outs[2 * n_ids].ptr; + try k_ptr.prefillLaunch(&t.base.r, arg, t.base.stream.handle, @intCast(item_count)); + try t.base.stream.synchronize(); + const written = try gpa.alloc(u8, bytes); + defer gpa.free(written); + try outs[big].download(0, written); + t.digest = std.hash.Wyhash.hash(t.digest, written); + var diff: usize = 0; + for (0..n_outs) |i| { + if (i == big) continue; + const d = try data.sameOnDevice(outs[big], outs[i], bytes); + if (d != 0) { + const what: []const u8 = if (i < 2 * n_ids) ids[i % n_ids].id else "the engine's pick"; + std.debug.print("{s} differs from {s} in {d} words\n", .{ what, ids[big].id, d }); + const ha = try gpa.alloc(f32, m * n); + defer gpa.free(ha); + const hb2 = try gpa.alloc(f32, m * n); + defer gpa.free(hb2); + try outs[big].download(0, std.mem.sliceAsBytes(ha)); + try outs[i].download(0, std.mem.sliceAsBytes(hb2)); + var shown: usize = 0; + for (ha, hb2, 0..) |u, v, at| { + if (@as(u32, @bitCast(u)) != @as(u32, @bitCast(v)) and shown < 12) { + std.debug.print(" row {d} col {d}: {e} vs {e}\n", .{ at / n, at % n, u, v }); + shown += 1; + } + } + } + diff += d; + } + return diff; +} + +/// The router's logits through the wave-an-expert kernel and the 64 x 64 tiles at `r` rows: the words that differ. +fn routerProduct(t: *Rig, r: usize, d: usize, e: usize) !usize { + const hx = try data.fill(gpa, u16, r * d, &t.rng, if (t.fp16) data.makeX16 else data.makeXB); + defer gpa.free(hx); + const hw = try gpa.alloc(f32, e * d); + defer gpa.free(hw); + for (hw) |*v| v.* = data.fine(&t.rng); + var x = try Buffer.fromHost(t.base, hx); + defer x.free(); + var w = try Buffer.fromHost(t.base, hw); + defer w.free(); + var outs: [2]Buffer = undefined; + for (&outs, 0..) |*o, i| { + o.* = try Buffer.alloc(t.base, r * e * 4); + errdefer for (outs[0..i]) |*f| f.free(); + try o.fill8(0xA5, null); + } + defer for (&outs) |*o| o.free(); + for (outs, [_]bool{ true, false }) |o, small| { + try t.base.on.routerWith(@ptrFromInt(x.ptr), if (t.fp16) 1 else 2, @ptrFromInt(w.ptr), @ptrFromInt(o.ptr), @intCast(r), @intCast(d), @intCast(e), t.base.stream.handle, small); + } + try t.base.stream.synchronize(); + const written = try gpa.alloc(u8, r * e * 4); + defer gpa.free(written); + try outs[0].download(0, written); + t.digest = std.hash.Wyhash.hash(t.digest, written); + return data.sameOnDevice(outs[0], outs[1], r * e * 4); +} + +/// Prefill's short blocks against the 128-row one at every `tier_rows`, dense and routed: any differing word fails. +fn tiers(t: *Rig) !usize { + var ran: usize = 0; + for (shapes.widths) |bits_u| for (shapes.groups) |group_u| for (tier_rows) |m| for ([_]bool{ false, true }) |routed| { + // n off every block width, k a few stages or a long odd run + const bits: c_int = bits_u; + const group: c_int = group_u; + const ks = [_]usize{ 3 * @as(usize, @intCast(group)), if (group == 32) 2080 else 1024 }; + for (ks, 0..) |k, j| { + const n: usize = if (j == 0) 97 else 288; + const diff = try tierProduct(t, m, n, k, bits, group, routed); + try base.expect(diff == 0, "gemm tiers m{d} n{d} k{d} b{d} g{d} routed {}: {d} words differ from the 128-row block", .{ m, n, k, bits, group, routed, diff }); + ran += 1; + } + }; + for (tier_rows) |r| { + for ([_]usize{ 96, 2048 }) |d| { + const diff = try routerProduct(t, r, d, 259); + try base.expect(diff == 0, "router logits r{d} d{d}: {d} words differ between the wave-an-expert kernel and the tiles", .{ r, d, diff }); + ran += 1; + } + } + return ran; +} + +/// Decode: the rows of a lane round's launch against each row alone, plain products and routed plans. +pub fn decode(t: *Rig) !void { + var rng: data.Rng = .{ .state = 0x9E3779B97F4A7C15 }; + var bad: usize = 0; + for (cases) |c| for ([_]bool{ false, true }) |half| { + bad += try product(t, &rng, c, half); + }; + for (routed_cases) |c| for ([_]bool{ false, true }) |pair| { + bad += try routedProduct(t, &rng, c, pair); + }; + try base.expect(bad == 0, "rows decode: {d} rows differ from the same row alone", .{bad}); +} + +/// Prefill: every tile the registry picks between by rows, at every row count, width and group. +pub fn prefill(t: *Rig) !void { + try base.expect(try tiers(t) > 0, "rows prefill: no product ran", .{}); +} + +test "a decode row writes the same bytes alone and in a round of 2 to 32, dense and routed, fp32 and rounded" { + const b = try base.Rig.open(1 << 20); + defer b.close(); + var rig = Rig.open(b); + try decode(&rig); +} + +test "a prompt row writes the same bytes in every tile, dense and routed, every width and group, and the router's logits" { + const b = try base.Rig.open(1 << 20); + defer b.close(); + var rig = Rig.open(b); + try prefill(&rig); +} diff --git a/zig/src/hip/kernel_tests/attention.zig b/zig/src/hip/kernel_tests/attention.zig new file mode 100644 index 00000000000..b46fda64c2c --- /dev/null +++ b/zig/src/hip/kernel_tests/attention.zig @@ -0,0 +1,225 @@ +//! Attention: planned decode over pages and the paged prompt tile against their flat forms (same bits) and float64. +const std = @import("std"); +const rig = @import("rig.zig"); +const Rig = rig.Rig; +const gpa = rig.gpa; +const at = rig.at; +const plan = @import("../launches/plan.zig"); +const DeviceBuffer = @import("../memory.zig").DeviceBuffer; + +const page = 64; + +/// A cache of `kv_heads` heads and `span` positions in the activation type, flat (kv_heads, span, d) and paged. +const Cache = struct { + k: []u16, + v: []u16, + /// Position block i lives in page table[i]. + table: []u32, + + fn make(t: *Rig, rng: *rig.Rng, kv_heads: usize, span: usize, d: usize) !Cache { + const c: Cache = .{ .k = try gpa.alloc(u16, kv_heads * span * d), .v = try gpa.alloc(u16, kv_heads * span * d), .table = try gpa.alloc(u32, span / page) }; + for (c.k) |*x| x.* = t.bits(rng.unit()); + for (c.v) |*x| x.* = t.bits(rng.unit()); + // a permutation, so a walk that ignored the table would read the wrong keys + for (c.table, 0..) |*p, i| p.* = @intCast((i * 5 + 3) % c.table.len); + return c; + } + + fn free(c: Cache) void { + gpa.free(c.k); + gpa.free(c.v); + gpa.free(c.table); + } + + /// The pool layout of decode/pages.hpp: ((h * count + page) * 64 + slot) * d. + fn pool(c: Cache, src: []const u16, kv_heads: usize, span: usize, d: usize) ![]u16 { + const out = try gpa.alloc(u16, src.len); + const count = span / page; + for (0..kv_heads) |h| for (0..span) |pos| { + const to = ((h * count + c.table[pos / page]) * page + pos % page) * d; + @memcpy(out[to..][0..d], src[(h * span + pos) * d ..][0..d]); + }; + return out; + } +}; + +/// softmax(q . k * scale) v in float64 for one query of `head` seeing positions [0, visible). +fn reference(t: *const Rig, c: Cache, q: []const f32, head: usize, group: usize, span: usize, d: usize, visible: usize, scale: f64, out: []f64) void { + const kv = head / group; + var top: f64 = -std.math.inf(f64); + var scores: [4096]f64 = undefined; + for (0..visible) |key| { + var dot: f64 = 0; + for (0..d) |j| dot += @as(f64, q[j]) * t.value(c.k[(kv * span + key) * d + j]); + scores[key] = dot * scale; + top = @max(top, scores[key]); + } + var sum: f64 = 0; + for (scores[0..visible]) |*s| { + s.* = @exp(s.* - top); + sum += s.*; + } + @memset(out[0..d], 0); + for (0..visible) |key| for (0..d) |j| { + out[j] += scores[key] / sum * t.value(c.v[(kv * span + key) * d + j]); + }; +} + +fn worst(got: []const f32, want: []const f64) f64 { + var scale: f64 = 0; + var max: f64 = 0; + for (got, want) |g, w| { + max = @max(max, @abs(@as(f64, g) - w)); + scale = @max(scale, @abs(w)); + } + return max / scale; +} + +/// Rows at positions `pos` over one slot's cache: the planned walk (grouped heads, pages) and the flat walk agree. +fn decode(t: *Rig, rng: *rig.Rng, heads: usize, kv_heads: usize, d: usize, pos: []const i32) !void { + const span: usize = 1024; + const rows = pos.len; + const group = heads / kv_heads; + const scale: f32 = 1 / @sqrt(@as(f32, @floatFromInt(d))); + const c = try Cache.make(t, rng, kv_heads, span, d); + defer c.free(); + const hq = try gpa.alloc(f32, rows * heads * d); + defer gpa.free(hq); + for (hq) |*x| x.* = rng.unit(); + var q = try t.upload(hq); + defer q.free(); + var k = try t.upload(c.k); + defer k.free(); + var v = try t.upload(c.v); + defer v.free(); + const pk = try c.pool(c.k, kv_heads, span, d); + defer gpa.free(pk); + const pv = try c.pool(c.v, kv_heads, span, d); + defer gpa.free(pv); + var pool_k = try t.upload(pk); + defer pool_k.free(); + var pool_v = try t.upload(pv); + defer pool_v.free(); + // one slot: descriptor [cached, kept, k pool, v pool], then its page table + const words = 4; + const desc = try gpa.alloc(u64, words + (c.table.len + 1) / 2); + defer gpa.free(desc); + @memset(desc, 0); + desc[2] = at(pool_k); + desc[3] = at(pool_v); + @memcpy(std.mem.sliceAsBytes(desc[words..])[0 .. c.table.len * 4], std.mem.sliceAsBytes(c.table)); + var dev_desc = try t.upload(desc); + defer dev_desc.free(); + const desc_ptr = [_]u64{at(dev_desc)}; + var descs = try t.upload(&desc_ptr); + defer descs.free(); + var dev_pos = try t.upload(pos); + defer dev_pos.free(); + const zeros = try gpa.alloc(i32, rows); + defer gpa.free(zeros); + @memset(zeros, 0); + var slot = try t.upload(zeros); + defer slot.free(); + const first = [_]i32{0}; + const count = [_]i32{@intCast(rows)}; + var dev_first = try t.upload(&first); + defer dev_first.free(); + var dev_count = try t.upload(&count); + defer dev_count.free(); + const tiles = span / 128; + var scores = try t.alloc(rows * heads * span * 4); + defer scores.free(); + var stats = try t.alloc(rows * heads * 2 * 4); + defer stats.free(); + var partials = try t.alloc(rows * heads * tiles * d * 4); + defer partials.free(); + var outs: [2]DeviceBuffer = .{ try t.alloc(rows * heads * d * 4), try t.alloc(rows * heads * d * 4) }; + defer for (&outs) |*o| o.free(); + const s = t.stream.handle; + try t.on.tf_causal(@ptrFromInt(at(q)), @ptrFromInt(at(k)), @ptrFromInt(at(v)), @ptrFromInt(at(outs[0])), @intCast(rows), 1, @intCast(span), @intCast(heads), @intCast(kv_heads), @intCast(d), scale, 0, 0, @intCast(span * d), @intCast(d), 0, @intCast(span * d), @intCast(d), if (t.bf16) 1 else 0, @ptrFromInt(at(scores)), @ptrFromInt(at(stats)), @ptrFromInt(at(partials)), s, @ptrFromInt(at(dev_pos))); + const p: plan.PlanRef = .{ .rows = rows, .slots = 1, .args = .{ .pos = at(dev_pos), .slot = at(slot), .first = at(dev_first), .count = at(dev_count), .desc = at(descs), .pages = words, .pool = @intCast(c.table.len) } }; + try t.on.planCausal(at(q), at(outs[1]), at(scores), at(stats), at(partials), p, 0, heads, kv_heads, d, span, scale, t.kind(), s); + try t.stream.synchronize(); + const flat = try rig.download(f32, outs[0]); + defer gpa.free(flat); + const planned = try rig.download(f32, outs[1]); + defer gpa.free(planned); + try std.testing.expectEqualSlices(u32, @ptrCast(flat), @ptrCast(planned)); + const want = try gpa.alloc(f64, rows * heads * d); + defer gpa.free(want); + for (0..rows) |r| for (0..heads) |h| { + const at_q = (r * heads + h) * d; + reference(t, c, hq[at_q..][0..d], h, group, span, d, @intCast(pos[r] + 1), scale, want[at_q..][0..d]); + }; + try std.testing.expect(worst(planned, want) < 1e-5); +} + +test "the planned decode walk over pages writes the flat walk's bits for grouped heads, within 1e-5 of float64" { + const t = try Rig.open(1 << 20); + defer t.close(); + var rng: rig.Rng = .{ .state = 0xA77E57 }; + const pos = [_]i32{ 0, 37, 300, 1023 }; + try decode(t, &rng, 16, 2, 256, &pos); // 8 query heads a KV head, Qwen3.6-35B-A3B's attention + try decode(t, &rng, 24, 4, 256, &pos); // 6, Qwen3.8-27B + try decode(t, &rng, 16, 4, 128, &pos); // 4 + try decode(t, &rng, 4, 4, 128, &pos); // no sharing +} + +/// A prompt of `qlen` queries from `q_pos0` over `span` positions: the paged 64-row tile writes the flat tile's bits. +fn prompt(t: *Rig, rng: *rig.Rng, heads: usize, kv_heads: usize, d: usize, qlen: usize, q_pos0: usize) !void { + const span = q_pos0 + qlen; + const group = heads / kv_heads; + const scale: f32 = 1 / @sqrt(@as(f32, @floatFromInt(d))); + const c = try Cache.make(t, rng, kv_heads, span, d); + defer c.free(); + const hq = try gpa.alloc(f32, heads * qlen * d); + defer gpa.free(hq); + for (hq) |*x| x.* = rng.unit(); + var q = try t.upload(hq); + defer q.free(); + var k = try t.upload(c.k); + defer k.free(); + var v = try t.upload(c.v); + defer v.free(); + const pk = try c.pool(c.k, kv_heads, span, d); + defer gpa.free(pk); + const pv = try c.pool(c.v, kv_heads, span, d); + defer gpa.free(pv); + var pool_k = try t.upload(pk); + defer pool_k.free(); + var pool_v = try t.upload(pv); + defer pool_v.free(); + var table = try t.upload(c.table); + defer table.free(); + var outs: [2]DeviceBuffer = .{ try t.alloc(heads * qlen * d * 4), try t.alloc(heads * qlen * d * 4) }; + defer for (&outs) |*o| o.free(); + const s = t.stream.handle; + const kind: c_int = if (t.bf16) 1 else 0; + try t.on.tf_causal(@ptrFromInt(at(q)), @ptrFromInt(at(k)), @ptrFromInt(at(v)), @ptrFromInt(at(outs[0])), 1, @intCast(qlen), @intCast(span), @intCast(heads), @intCast(kv_heads), @intCast(d), scale, @intCast(q_pos0), 0, @intCast(span * d), @intCast(d), 0, @intCast(span * d), @intCast(d), kind, null, null, null, s, null); + try t.on.pagedCausal(at(q), at(pool_k), at(pool_v), at(table), at(outs[1]), qlen, span, heads, kv_heads, d, scale, q_pos0, c.table.len, kind, s); + try t.stream.synchronize(); + const flat = try rig.download(f32, outs[0]); + defer gpa.free(flat); + const paged = try rig.download(f32, outs[1]); + defer gpa.free(paged); + try std.testing.expectEqualSlices(u32, @ptrCast(flat), @ptrCast(paged)); + // the tile rounds q to the cache's type once, so it sits within that type's rounding of float64 + const want = try gpa.alloc(f64, heads * qlen * d); + defer gpa.free(want); + for (0..heads) |h| for (0..qlen) |i| { + const at_q = (h * qlen + i) * d; + reference(t, c, hq[at_q..][0..d], h, group, span, d, q_pos0 + i + 1, scale, want[at_q..][0..d]); + }; + const bound: f64 = if (t.bf16) 2e-2 else 4e-3; + try std.testing.expect(worst(paged, want) < bound); +} + +test "the paged prompt tile writes the flat tile's bits, within the cache type's rounding of float64" { + const t = try Rig.open(1 << 20); + defer t.close(); + var rng: rig.Rng = .{ .state = 0x9A6ED }; + try prompt(t, &rng, 16, 2, 256, 128, 0); + try prompt(t, &rng, 16, 2, 256, 64, 192); + try prompt(t, &rng, 24, 4, 256, 192, 64); + try prompt(t, &rng, 16, 4, 128, 128, 128); +} diff --git a/zig/src/hip/kernel_tests/chain.zig b/zig/src/hip/kernel_tests/chain.zig new file mode 100644 index 00000000000..c2edd65a083 --- /dev/null +++ b/zig/src/hip/kernel_tests/chain.zig @@ -0,0 +1,222 @@ +//! The merged linear-attention and MoE-pick launches against the chains they replace: the same bytes. +const std = @import("std"); +const rig = @import("rig.zig"); +const Rig = rig.Rig; +const gpa = rig.gpa; +const at = rig.at; +const DeviceBuffer = @import("../memory.zig").DeviceBuffer; + +fn same(a: DeviceBuffer, b: DeviceBuffer) !void { + const ha = try rig.download(u8, a); + defer gpa.free(ha); + const hb = try rig.download(u8, b); + defer gpa.free(hb); + try std.testing.expectEqualSlices(u8, ha, hb); +} + +fn ptr(v: u64) ?*anyopaque { + return @ptrFromInt(v); +} + +/// The pick rule over `rows` rows of (experts + 1) logits: picks, weights, items and members alike. +fn select(t: *Rig, rng: *rig.Rng, rows: usize, experts: usize, top_k: usize) !void { + const slots = top_k + 1; + const capacity = slots + 7; + const logits = try gpa.alloc(f32, rows * (experts + 1)); + defer gpa.free(logits); + for (logits) |*v| v.* = rng.unit() * 4.0; + // equal logits: the lower index wins + for (0..rows) |r| logits[r * (experts + 1) + 5] = logits[r * (experts + 1) + 9]; + var dev_logits = try t.upload(logits); + defer dev_logits.free(); + var picks: [2]DeviceBuffer = undefined; + var wts: [2]DeviceBuffer = undefined; + var items: [2]DeviceBuffer = undefined; + var members: [2]DeviceBuffer = undefined; + for (0..2) |v| { + picks[v] = try t.alloc(rows * slots * 4); + wts[v] = try t.alloc(rows * slots * 4); + items[v] = try t.alloc(capacity * 12); + members[v] = try t.alloc(capacity * 4); + try members[v].fill8(0); + } + defer for (0..2) |v| { + picks[v].free(); + wts[v].free(); + items[v].free(); + members[v].free(); + }; + const plan = rows == 1; + for ([2]*const @import("../launches.zig").Launcher{ &t.off, &t.on }, 0..) |l, v| { + try l.tf_moe_select(@ptrFromInt(at(dev_logits)), @ptrFromInt(at(picks[v])), @ptrFromInt(at(wts[v])), if (plan) @ptrFromInt(at(items[v])) else null, if (plan) @ptrFromInt(at(members[v])) else null, @intCast(capacity), @intCast(rows), @intCast(experts), @intCast(top_k), t.stream.handle); + } + try t.stream.synchronize(); + try same(picks[0], picks[1]); + try same(wts[0], wts[1]); + if (plan) { + try same(items[0], items[1]); + try same(members[0], members[1]); + } +} + +/// A window's conv chain (cast, conv, three column copies, q and k norms, gate) against one launch. +fn conv(t: *Rig, rng: *rig.Rng, rows: usize) !void { + const kw: usize = 2048; + const vw: usize = 4096; + const ch = 2 * kw + vw; + const kernel: usize = 4; + const eps: f32 = 1e-6; + const vheads: usize = 32; + const hx = try gpa.alloc(u16, rows * ch); + defer gpa.free(hx); + for (hx) |*v| v.* = t.bits(rng.unit() * 2.0); + const hw = try gpa.alloc(f32, ch * kernel); + defer gpa.free(hw); + for (hw) |*v| v.* = rng.unit() / 2.0; + const hs = try gpa.alloc(f32, (kernel - 1) * ch); + defer gpa.free(hs); + for (hs) |*v| v.* = rng.unit(); + const hn = try gpa.alloc(f32, 128 * 2); + defer gpa.free(hn); + for (hn) |*v| v.* = 1.0 + rng.unit() / 4.0; + const ha = try gpa.alloc(u16, rows * vheads); + defer gpa.free(ha); + for (ha) |*v| v.* = t.bits(rng.unit() * 3.0); + const hb = try gpa.alloc(u16, rows * vheads); + defer gpa.free(hb); + for (hb) |*v| v.* = t.bits(rng.unit() * 3.0); + const hlog = try gpa.alloc(f32, vheads * 2); + defer gpa.free(hlog); + for (hlog) |*v| v.* = rng.unit(); + var x = try t.upload(hx); + defer x.free(); + var weight = try t.upload(hw); + defer weight.free(); + var norm = try t.upload(hn); + defer norm.free(); + var dev_a = try t.upload(ha); + defer dev_a.free(); + var dev_b = try t.upload(hb); + defer dev_b.free(); + var dev_log = try t.upload(hlog); + defer dev_log.free(); + var xr = try t.alloc(rows * ch * 4); + defer xr.free(); + var mixed = try t.alloc(rows * ch * 4); + defer mixed.free(); + var bufs: [2][9]DeviceBuffer = undefined; // gate, beta, state, snaps, qc, kc, v, qn, kn + for (0..2) |v| { + bufs[v] = .{ + try t.alloc(rows * vheads * 4), try t.alloc(rows * vheads * 4), try t.upload(hs), + try t.alloc(rows * (kernel - 1) * ch * 4), try t.alloc(rows * kw * 4), try t.alloc(rows * kw * 4), + try t.alloc(rows * vw * 4), try t.alloc(rows * kw * 4), try t.alloc(rows * kw * 4), + }; + } + defer for (&bufs) |*set| for (set) |*b| b.free(); + const s = t.stream.handle; + const l = &t.on; + const heads = rows * (kw / 128); + const kind = t.kind(); + { + const b = bufs[0]; + try l.tf_cast(ptr(at(x)), kind, ptr(at(xr)), 0, @intCast(rows * ch), s); + if (rows == 1) { + try l.tf_conv_decode(@ptrFromInt(at(xr)), @ptrFromInt(at(weight)), @ptrFromInt(at(b[2])), @ptrFromInt(at(mixed)), 1, @intCast(ch), @intCast(kernel), s); + } else { + try l.tf_conv_rows(@ptrFromInt(at(xr)), @ptrFromInt(at(weight)), @ptrFromInt(at(b[2])), @ptrFromInt(at(mixed)), @ptrFromInt(at(b[3])), @intCast(rows), @intCast(ch), @intCast(kernel), s); + } + try l.tf_copy_cols(ptr(at(mixed)), @intCast(ch), 0, ptr(at(b[4])), 0, @intCast(rows), @intCast(kw), s); + try l.tf_copy_cols(ptr(at(mixed)), @intCast(ch), @intCast(kw), ptr(at(b[5])), 0, @intCast(rows), @intCast(kw), s); + try l.tf_copy_cols(ptr(at(mixed)), @intCast(ch), @intCast(2 * kw), ptr(at(b[6])), 0, @intCast(rows), @intCast(vw), s); + try l.tf_rms(ptr(at(b[4])), @ptrFromInt(at(norm)), ptr(at(b[7])), 0, @intCast(heads), 128, eps, s); + try l.tf_rms(ptr(at(b[5])), @ptrFromInt(at(norm) + 512), ptr(at(b[8])), 0, @intCast(heads), 128, eps, s); + try l.tf_gdn_gate(ptr(at(dev_a)), ptr(at(dev_b)), kind, @ptrFromInt(at(dev_log)), @ptrFromInt(at(dev_log) + 128), @ptrFromInt(at(b[0])), @ptrFromInt(at(b[1])), @intCast(rows * 32), 32, s); + } + { + const b = bufs[1]; + try l.tf_conv_split(.{ + .x = at(x), + .kind = kind, + .weight = at(weight), + .state = at(b[2]), + .states = if (rows > 1) at(b[3]) else 0, + .qn = at(b[7]), + .kn = at(b[8]), + .v = at(b[6]), + .channels = @intCast(ch), + .kernel = @intCast(kernel), + .rows = @intCast(rows), + .kw = @intCast(kw), + .vw = @intCast(vw), + .qw = at(norm), + .kw_w = at(norm) + 512, + .eps = eps, + .norm = 128, + .ga = at(dev_a), + .gb = at(dev_b), + .a_log = at(dev_log), + .dt_bias = at(dev_log) + 128, + .gate = at(b[0]), + .beta = at(b[1]), + .gcount = @intCast(rows * 32), + .heads = 32, + }, s); + } + try t.stream.synchronize(); + // gate, beta, state, snapshots (several rows only), v, q norm, k norm + for ([_]usize{ 0, 1, 2, 6, 7, 8 }) |i| try same(bufs[0][i], bufs[1][i]); + if (rows > 1) try same(bufs[0][3], bufs[1][3]); +} + +/// The linear attention's gated norm: rms then gnorm_silu against one launch. +fn gnorm(t: *Rig, rng: *rig.Rng, rows: usize) !void { + const n = rows * 32 * 128; + const eps: f32 = 1e-6; + const hy = try gpa.alloc(f32, n); + defer gpa.free(hy); + for (hy) |*v| v.* = rng.unit() * 3.0; + const hz = try gpa.alloc(u16, n); + defer gpa.free(hz); + for (hz) |*v| v.* = t.bits(rng.unit() * 4.0); + const hn = try gpa.alloc(f32, 128); + defer gpa.free(hn); + for (hn) |*v| v.* = 1.0 + rng.unit() / 4.0; + var y = try t.upload(hy); + defer y.free(); + var z = try t.upload(hz); + defer z.free(); + var weight = try t.upload(hn); + defer weight.free(); + var yn = try t.alloc(n * 4); + defer yn.free(); + var outs: [2]DeviceBuffer = .{ try t.alloc(n * 2), try t.alloc(n * 2) }; + defer for (&outs) |*o| o.free(); + const s = t.stream.handle; + try t.on.tf_rms(ptr(at(y)), @ptrFromInt(at(weight)), ptr(at(yn)), 0, @intCast(rows * 32), 128, eps, s); + try t.on.tf_gnorm_silu(@ptrFromInt(at(yn)), ptr(at(z)), ptr(at(outs[0])), t.kind(), @intCast(n), s); + try t.on.tf_gnorm_out(@ptrFromInt(at(y)), @ptrFromInt(at(weight)), ptr(at(z)), ptr(at(outs[1])), t.kind(), @intCast(rows * 32), 128, eps, s); + try t.stream.synchronize(); + try same(outs[0], outs[1]); +} + +test "the merged MoE pick writes the scanning kernel's picks, weights, items and members" { + const t = try Rig.open(1 << 20); + defer t.close(); + var rng: rig.Rng = .{ .state = 0x9E3779B97F4A7C15 }; + for ([_]usize{ 1, 4, 16 }) |rows| try select(t, &rng, rows, 256, 8); + try select(t, &rng, 1, 128, 6); +} + +test "the merged conv split writes the chain's state, snapshots, q, k, v, gate and beta" { + const t = try Rig.open(1 << 20); + defer t.close(); + var rng: rig.Rng = .{ .state = 0x9E3779B97F4A7C15 }; + for ([_]usize{ 1, 2, 4, 16 }) |rows| try conv(t, &rng, rows); +} + +test "the merged gated norm writes rms then gnorm_silu's bytes" { + const t = try Rig.open(1 << 20); + defer t.close(); + var rng: rig.Rng = .{ .state = 0x9E3779B97F4A7C15 }; + for ([_]usize{ 1, 4, 16, 128 }) |rows| try gnorm(t, &rng, rows); +} diff --git a/zig/src/hip/kernel_tests/decode.zig b/zig/src/hip/kernel_tests/decode.zig new file mode 100644 index 00000000000..5c85b799cab --- /dev/null +++ b/zig/src/hip/kernel_tests/decode.zig @@ -0,0 +1,303 @@ +//! The merged decode-step launches against the launches they replace, each against a float64 reference. +const std = @import("std"); +const rig = @import("rig.zig"); +const Rig = rig.Rig; +const gpa = rig.gpa; +const at = rig.at; +const Launcher = @import("../launches.zig").Launcher; + +fn p(b: anytype) ?*anyopaque { + return @ptrFromInt(at(b)); +} + +/// The router's logits for `rows` rows over (experts, d) fp32 weights: the merged launch no further from float64. +fn router(t: *Rig, rng: *rig.Rng, rows: usize, d: usize, experts: usize) !void { + const hx = try gpa.alloc(u16, rows * d); + defer gpa.free(hx); + for (hx) |*v| v.* = t.bits(rng.unit()); + const hw = try gpa.alloc(f32, experts * d); + defer gpa.free(hw); + for (hw) |*v| v.* = rng.unit() / 8.0; + var x = try t.upload(hx); + defer x.free(); + var w = try t.upload(hw); + defer w.free(); + var max_err: [2]f64 = .{ 0, 0 }; + for ([2]*const Launcher{ &t.off, &t.on }, 0..) |l, v| { + var out = try t.alloc(rows * experts * 4); + defer out.free(); + try l.tf_moe_router(p(x), t.kind(), @ptrFromInt(at(w)), @ptrFromInt(at(out)), @intCast(rows), @intCast(d), @intCast(experts), t.stream.handle); + try t.stream.synchronize(); + const got = try rig.download(f32, out); + defer gpa.free(got); + for (0..rows) |r| for (0..experts) |e| { + var y: f64 = 0; + var norm: f64 = 0; + for (0..d) |i| { + const term = t.value(hx[r * d + i]) * @as(f64, hw[e * d + i]); + y += term; + norm += @abs(term); + } + max_err[v] = @max(max_err[v], @abs(@as(f64, got[r * experts + e]) - y) / norm); + }; + } + try std.testing.expect(max_err[1] <= 2 * max_err[0] + 1e-9); +} + +/// x = x + y (or the slots' weighted sum) and the next norm: one merged launch against combine, add and norm. +fn tails(t: *Rig, rng: *rig.Rng, rows: usize, width: usize, slots: usize) !void { + const n = rows * width; + const eps: f32 = 1e-6; + const hx = try gpa.alloc(u16, n); + defer gpa.free(hx); + for (hx) |*v| v.* = t.bits(rng.unit()); + const hy16 = try gpa.alloc(u16, if (slots > 0) 0 else n); + defer gpa.free(hy16); + const hy32 = try gpa.alloc(f32, if (slots > 0) rows * slots * width else 0); + defer gpa.free(hy32); + for (hy16) |*v| v.* = t.bits(rng.unit() / 8.0); + for (hy32) |*v| v.* = rng.unit() / 8.0; + const hw = try gpa.alloc(f32, rows * @max(slots, 1)); + defer gpa.free(hw); + for (hw) |*v| v.* = (rng.unit() + 1.0) / @as(f32, @floatFromInt(@max(slots, 1))); + const hn = try gpa.alloc(f32, width); + defer gpa.free(hn); + for (hn) |*v| v.* = 1.0 + rng.unit() / 4.0; + var y = if (slots > 0) try t.upload(hy32) else try t.upload(hy16); + defer y.free(); + var wts = try t.upload(hw); + defer wts.free(); + var weight = try t.upload(hn); + defer weight.free(); + var tmp = try t.alloc(n * 2); + defer tmp.free(); + var errs: [2][2]f64 = .{ .{ 0, 0 }, .{ 0, 0 } }; + for (0..2) |v| { + var x = try t.upload(hx); + defer x.free(); + var normed = try t.alloc(n * 2); + defer normed.free(); + const s = t.stream.handle; + if (v == 0) { + const sum = if (slots > 0) p(tmp) else p(y); + if (slots > 0) try t.off.tf_moe_combine(@ptrFromInt(at(y)), @ptrFromInt(at(wts)), sum, t.kind(), @intCast(rows), @intCast(slots), @intCast(width), s); + try t.off.tf_add(p(x), sum, p(x), t.kind(), @intCast(n), s); + try t.off.tf_rms(p(x), @ptrFromInt(at(weight)), p(normed), t.kind(), @intCast(rows), @intCast(width), eps, s); + } else { + try t.on.tf_tail(p(x), p(y), if (slots > 0) @ptrFromInt(at(wts)) else null, @ptrFromInt(at(weight)), p(normed), t.kind(), @intCast(rows), @intCast(slots), @intCast(width), eps, s); + } + try t.stream.synchronize(); + const gx = try rig.download(u16, x); + defer gpa.free(gx); + const gn = try rig.download(u16, normed); + defer gpa.free(gn); + const want = try gpa.alloc(f64, width); + defer gpa.free(want); + for (0..rows) |r| { + var sq: f64 = 0; + var top: f64 = 0; + for (0..width) |c| { + var add: f64 = 0; + if (slots > 0) { + for (0..slots) |sl| add += @as(f64, hy32[(r * slots + sl) * width + c]) * @as(f64, hw[r * slots + sl]); + } else add = t.value(hy16[r * width + c]); + want[c] = t.value(hx[r * width + c]) + add; + sq += want[c] * want[c]; + top = @max(top, @abs(want[c])); + } + const inv = 1.0 / @sqrt(sq / @as(f64, @floatFromInt(width)) + eps); + for (0..width) |c| { + errs[v][0] = @max(errs[v][0], @abs(t.value(gx[r * width + c]) - want[c]) / top); + errs[v][1] = @max(errs[v][1], @abs(t.value(gn[r * width + c]) - want[c] * inv * hn[c]) / (top * inv * 1.25)); + } + } + } + try std.testing.expect(errs[1][0] <= 2 * errs[0][0] + 1e-7); + try std.testing.expect(errs[1][1] <= 2 * errs[0][1] + 1e-7); +} + +test "the merged router launch is no further from float64 than twice the launch it replaces" { + const t = try Rig.open(1 << 20); + defer t.close(); + var rng: rig.Rng = .{ .state = 0x9E3779B97F4A7C15 }; + for ([_]usize{ 1, 2, 4, 8 }) |rows| try router(t, &rng, rows, 2048, 257); +} + +test "the merged residual-and-norm tails are no further from float64 than twice the launches they replace" { + const t = try Rig.open(1 << 20); + defer t.close(); + var rng: rig.Rng = .{ .state = 0x9E3779B97F4A7C15 }; + for ([_]usize{ 1, 4, 16 }) |rows| { + try tails(t, &rng, rows, 2048, 0); + try tails(t, &rng, rows, 2048, 9); + } + try tails(t, &rng, 1, 4096, 0); +} + +const affine = @import("../launches/affine.zig"); +const ref = @import("affine/reference.zig"); + +/// A random packed product on the host and the device: (n, k) at `bits` and `group`, bf16 tables, `experts` stacked. +const Matrix = struct { + n: usize, + k: usize, + bits: usize, + group: usize, + words: []u32, + scale: []u16, + bias: []u16, + dev: [3]@import("../memory.zig").DeviceBuffer, + + fn init(t: *Rig, rng: *rig.Rng, n: usize, k: usize, bits: usize, group_size: usize, experts: usize) !Matrix { + var m: Matrix = .{ .n = n, .k = k, .bits = bits, .group = group_size, .words = undefined, .scale = undefined, .bias = undefined, .dev = undefined }; + m.words = try gpa.alloc(u32, experts * n * k * bits / 32); + m.scale = try gpa.alloc(u16, experts * n * k / group_size); + m.bias = try gpa.alloc(u16, m.scale.len); + for (m.words) |*w| w.* = @truncate(rng.next() >> 16); + for (m.scale) |*v| v.* = rig.bf16Bits((rng.unit() + 1.0) / 16.0); + for (m.bias) |*v| v.* = rig.bf16Bits(rng.unit() / 2.0); + m.dev = .{ try t.upload(m.words), try t.upload(m.scale), try t.upload(m.bias) }; + return m; + } + + fn deinit(m: *Matrix) void { + gpa.free(m.words); + gpa.free(m.scale); + gpa.free(m.bias); + for (&m.dev) |*b| b.free(); + } + + fn problem(m: Matrix, t: *const Rig, x: []const u16) ref.Problem { + return .{ .fp16 = !t.bf16, .n = m.n, .k = m.k, .bits = m.bits, .group = m.group, .x = x, .words = m.words, .scale = m.scale, .bias = m.bias }; + } + + fn arg(m: Matrix, t: *const Rig, x: u64, rows: usize, out: u64) affine.Arg { + return .{ + .x = x, + .words = at(m.dev[0]), + .scale = .{ .p = at(m.dev[1]), .kind = 1 }, + .bias = .{ .p = at(m.dev[2]), .kind = 1 }, + .out = out, + .m = @intCast(rows), + .n = @intCast(m.n), + .k = @intCast(m.k), + .bits = @intCast(m.bits), + .group = @intCast(m.group), + .fp16 = @intFromBool(!t.bf16), + }; + } +}; + +/// Up to four products sharing x in one launch against one launch each: no further from float64 than twice that. +fn group(t: *Rig, rng: *rig.Rng, rows: usize, ns: []const usize, k: usize, bits: usize, group_size: usize) !void { + const hx = try gpa.alloc(u16, rows * k); + defer gpa.free(hx); + for (hx) |*v| v.* = t.bits(rng.unit()); + var x = try t.upload(hx); + defer x.free(); + var ms: [4]Matrix = undefined; + var outs: [2][4]@import("../memory.zig").DeviceBuffer = undefined; + for (ns, 0..) |n, i| { + ms[i] = try Matrix.init(t, rng, n, k, bits, group_size, 1); + for (&outs) |*o| o[i] = try t.alloc(rows * n * 2); + } + defer for (ns, 0..) |_, i| { + ms[i].deinit(); + for (&outs) |*o| o[i].free(); + }; + const kernels = &t.on.affine; + for (ms[0..ns.len], 0..) |m, i| try kernels.run(&t.r, m.arg(t, at(x), rows, at(outs[0][i])), 4, t.stream.handle, 0, 1, true); + var sides: [4]affine.Side = undefined; + for (ms[0..ns.len], 0..) |m, i| sides[i] = .{ .words = at(m.dev[0]), .scale = at(m.dev[1]), .bias = at(m.dev[2]), .n = @intCast(m.n), .out = at(outs[1][i]) }; + try kernels.groupRun(&t.r, ms[0].arg(t, at(x), rows, 0), sides[0..ns.len], true, t.stream.handle); + try t.stream.synchronize(); + var errs: [2]f64 = .{ 0, 0 }; + for (0..2) |v| for (ns, 0..) |n, i| { + const got = try rig.download(u16, outs[v][i]); + defer gpa.free(got); + const prob = ms[i].problem(t, hx); + for (0..rows) |r| for (0..@min(n, 12)) |ci| { + const col = ci * (n - 1) / @max(@min(n, 12) - 1, 1); + const want = ref.reference(prob, r, 0, col); + errs[v] = @max(errs[v], @abs(t.value(got[r * n + col]) - want.y) / want.norm); + }; + }; + try std.testing.expect(errs[1] <= 2 * errs[0] + 1e-9); +} + +/// A token's routed gate and up, then the activation, against one launch with the activation as epilogue. +fn pair(t: *Rig, rng: *rig.Rng, rows: usize, width: usize, k: usize, bits: usize, group_size: usize) !void { + const experts = 64; + const slots = 9; + const pairs = rows * slots; + var m = try Matrix.init(t, rng, 2 * width, k, bits, group_size, experts); + defer m.deinit(); + const hx = try gpa.alloc(u16, rows * k); + defer gpa.free(hx); + for (hx) |*v| v.* = t.bits(rng.unit()); + var x = try t.upload(hx); + defer x.free(); + // a token's pairs are its slots; one pair an item + const pick = try gpa.alloc(u32, pairs); + defer gpa.free(pick); + for (pick) |*e| e.* = @intCast(rng.next() % experts); + const items = try gpa.alloc(i32, pairs * 3); + defer gpa.free(items); + const members = try gpa.alloc(i32, pairs); + defer gpa.free(members); + for (0..pairs) |i| { + items[3 * i ..][0..3].* = .{ @intCast(pick[i]), @intCast(i), 1 }; + members[i] = @intCast(i); + } + var dev_items = try t.upload(items); + defer dev_items.free(); + var dev_members = try t.upload(members); + defer dev_members.free(); + var both = try t.alloc(pairs * 2 * width * 4); + defer both.free(); + var acts: [2]@import("../memory.zig").DeviceBuffer = .{ try t.alloc(pairs * width * 2), try t.alloc(pairs * width * 2) }; + defer for (&acts) |*a| a.free(); + const kernels = &t.on.affine; + var a = m.arg(t, at(x), rows, at(both)); + a.route = .{ .items = at(dev_items), .members = at(dev_members), .x_div = slots }; + try kernels.routedWith(&t.r, a, @intCast(pairs), t.stream.handle, .gemm); + try t.off.tf_moe_act(@ptrFromInt(at(both)), @ptrFromInt(at(acts[0])), t.kind(), @intCast(pairs), @intCast(width), 0, t.stream.handle); + a.out = 0; + a.out16 = at(acts[1]); + try std.testing.expect(try kernels.pairRun(&t.r, a, 0, @intCast(pairs), t.stream.handle)); + try t.stream.synchronize(); + var errs: [2]f64 = .{ 0, 0 }; + const prob = m.problem(t, hx); + for (0..2) |v| { + const got = try rig.download(u16, acts[v]); + defer gpa.free(got); + for (0..pairs) |pi| for (0..12) |ci| { + const col = ci * (width - 1) / 11; + const g = ref.reference(prob, pi / slots, pick[pi], col); + const u = ref.reference(prob, pi / slots, pick[pi], col + width); + const want = g.y / (1.0 + @exp(-g.y)) * u.y; + errs[v] = @max(errs[v], @abs(t.value(got[pi * width + col]) - want) / @max(@abs(want), 0.01)); + }; + } + try std.testing.expect(errs[1] <= 2 * errs[0] + 1e-9); +} + +test "products sharing x in one launch are no further from float64 than twice one launch each" { + const t = try Rig.open(1 << 20); + defer t.close(); + var rng: rig.Rng = .{ .state = 0x9E3779B97F4A7C15 }; + for ([_]usize{ 1, 2, 4, 8, 16 }) |rows| try group(t, &rng, rows, &.{ 8192, 4096, 32, 32 }, 2048, 4, 64); + try group(t, &rng, 1, &.{ 8192, 512, 512 }, 2048, 4, 64); + try group(t, &rng, 1, &.{ 12288, 12288 }, 4096, 6, 64); + try group(t, &rng, 4, &.{ 4096, 4096 }, 4096, 8, 128); + try group(t, &rng, 2, &.{ 1024, 96, 96 }, 2048, 3, 32); +} + +test "the routed gate and up with its activation in one launch is no further from float64 than twice the two launches" { + const t = try Rig.open(1 << 20); + defer t.close(); + var rng: rig.Rng = .{ .state = 0x9E3779B97F4A7C15 }; + for ([_]usize{ 1, 2, 4 }) |rows| try pair(t, &rng, rows, 512, 2048, 4, 64); + try pair(t, &rng, 1, 768, 2048, 6, 64); + try pair(t, &rng, 1, 512, 2048, 4, 128); +} diff --git a/zig/src/hip/kernel_tests/gdn.zig b/zig/src/hip/kernel_tests/gdn.zig new file mode 100644 index 00000000000..fe6b8922da6 --- /dev/null +++ b/zig/src/hip/kernel_tests/gdn.zig @@ -0,0 +1,197 @@ +//! The DeltaNet recurrence against a float64 recurrence on random inputs, and the same bits however a prompt is cut. +const std = @import("std"); +const rig = @import("rig.zig"); +const Rig = rig.Rig; +const gpa = rig.gpa; +const DeviceBuffer = @import("../memory.zig").DeviceBuffer; + +const d = 128; +const Shape = struct { length: usize, key_heads: usize, value_heads: usize }; + +const Inputs = struct { + q: []f32, + k: []f32, + v: []f32, + gate: []f32, + beta: []f32, + state: []f32, + + /// L2-normalized q and k, gates exp(-A softplus(x)) in (0, 1], beta = sigmoid, a state of 0.1 scale. + fn make(sh: Shape, seed: u64) !Inputs { + var rng: rig.Rng = .{ .state = seed }; + const qk = sh.length * sh.key_heads * d; + const vy = sh.length * sh.value_heads * d; + const gb = sh.length * sh.value_heads; + const in: Inputs = .{ + .q = try gpa.alloc(f32, qk), + .k = try gpa.alloc(f32, qk), + .v = try gpa.alloc(f32, vy), + .gate = try gpa.alloc(f32, gb), + .beta = try gpa.alloc(f32, gb), + .state = try gpa.alloc(f32, sh.value_heads * d * d), + }; + for ([_][]f32{ in.q, in.k }) |a| { + for (0..a.len / d) |row| { + var ss: f64 = 0; + for (a[row * d ..][0..d]) |*x| { + const z = rng.normal(); + x.* = @floatCast(z); + ss += z * z; + } + const inv: f32 = @floatCast(1 / @sqrt(ss)); + for (a[row * d ..][0..d]) |*x| x.* *= inv; + } + } + for (in.v) |*x| x.* = @floatCast(rng.normal()); + for (in.state) |*x| x.* = @floatCast(0.1 * rng.normal()); + for (in.gate, in.beta, 0..) |*g, *b, i| { + const h = i % sh.value_heads; + const a_log = 0.5 + 7.5 * @as(f64, @floatFromInt(h)) / @as(f64, @floatFromInt(sh.value_heads)); + const x = rng.normal() - 2; + const sp = if (x > 20) x else @log(1 + @exp(x)); + g.* = @floatCast(@exp(-a_log * sp)); + b.* = @floatCast(1 / (1 + @exp(-rng.normal()))); + } + return in; + } + + fn free(in: Inputs) void { + for ([_][]f32{ in.q, in.k, in.v, in.gate, in.beta, in.state }) |a| gpa.free(a); + } +}; + +/// The recurrence in float64: y (L, Hv, d) and the final state. +fn reference(sh: Shape, in: Inputs, y: []f64, state: []f64) !void { + const s = try gpa.alloc(f64, d * d); + defer gpa.free(s); + const group = sh.value_heads / sh.key_heads; + for (0..sh.value_heads) |h| { + for (s, in.state[h * d * d ..][0 .. d * d]) |*a, b| a.* = b; + const kh = h / group; + for (0..sh.length) |t| { + const gb = t * sh.value_heads + h; + const decay: f64 = in.gate[gb]; + const beta: f64 = in.beta[gb]; + const k = in.k[(t * sh.key_heads + kh) * d ..][0..d]; + const q = in.q[(t * sh.key_heads + kh) * d ..][0..d]; + const v = in.v[gb * d ..][0..d]; + for (0..d) |r| { + const row = s[r * d ..][0..d]; + var kv: f64 = 0; + for (row, k) |*a, kk| { + a.* *= decay; + kv += a.* * kk; + } + const delta = (v[r] - kv) * beta; + var out: f64 = 0; + for (row, k, q) |*a, kk, qq| { + a.* += kk * delta; + out += a.* * qq; + } + y[gb * d + r] = out; + } + } + @memcpy(state[h * d * d ..][0 .. d * d], s); + } +} + +/// The largest error over the reference's largest value. +fn relative(got: []const f32, want: []const f64) f64 { + var scale: f64 = 0; + var max: f64 = 0; + for (got, want) |g, w| { + max = @max(max, @abs(@as(f64, g) - w)); + scale = @max(scale, @abs(w)); + } + return max / scale; +} + +/// One call of `length` rows from row `from`, state in place; q, k, v, gate and beta are offset to that row. +fn run(t: *Rig, sh: Shape, q: DeviceBuffer, k: DeviceBuffer, v: DeviceBuffer, gate: DeviceBuffer, beta: DeviceBuffer, state: DeviceBuffer, y: DeviceBuffer, from: usize, length: usize) !void { + const qk = from * sh.key_heads * d * 4; + const vy = from * sh.value_heads * d * 4; + const gb = from * sh.value_heads * 4; + try t.ops(&t.on).gatedDelta(rig.at(q) + qk, rig.at(k) + qk, rig.at(v) + vy, rig.at(gate) + gb, rig.at(beta) + gb, rig.at(state), rig.at(y) + vy, length, sh.key_heads, sh.value_heads, d, d, null); +} + +test "the DeltaNet stays within 5e-3 of the float64 recurrence at four lengths" { + const t = try Rig.open(1 << 30); + defer t.close(); + for ([_]Shape{ + .{ .length = 64, .key_heads = 2, .value_heads = 4 }, + .{ .length = 200, .key_heads = 2, .value_heads = 4 }, + .{ .length = 1000, .key_heads = 2, .value_heads = 4 }, + .{ .length = 4170, .key_heads = 2, .value_heads = 4 }, + }) |sh| { + const in = try Inputs.make(sh, 0x9e3779b97f4a7c15 + sh.length); + defer in.free(); + const ry = try gpa.alloc(f64, sh.length * sh.value_heads * d); + defer gpa.free(ry); + const rs = try gpa.alloc(f64, sh.value_heads * d * d); + defer gpa.free(rs); + try reference(sh, in, ry, rs); + var q = try t.upload(in.q); + defer q.free(); + var k = try t.upload(in.k); + defer k.free(); + var v = try t.upload(in.v); + defer v.free(); + var gate = try t.upload(in.gate); + defer gate.free(); + var beta = try t.upload(in.beta); + defer beta.free(); + var y = try t.alloc(ry.len * 4); + defer y.free(); + var state = try t.upload(in.state); + defer state.free(); + try run(t, sh, q, k, v, gate, beta, state, y, 0, sh.length); + try t.stream.synchronize(); + const gy = try rig.download(f32, y); + defer gpa.free(gy); + const gs = try rig.download(f32, state); + defer gpa.free(gs); + try std.testing.expect(relative(gy, ry) < 5e-3); + try std.testing.expect(relative(gs, rs) < 5e-3); + } +} + +test "a prompt cut on either side of 64 rows gives the same rows and state as one call" { + const t = try Rig.open(1 << 30); + defer t.close(); + const sh: Shape = .{ .length = 200, .key_heads = 2, .value_heads = 4 }; + const in = try Inputs.make(sh, 0x51ed); + defer in.free(); + var q = try t.upload(in.q); + defer q.free(); + var k = try t.upload(in.k); + defer k.free(); + var v = try t.upload(in.v); + defer v.free(); + var gate = try t.upload(in.gate); + defer gate.free(); + var beta = try t.upload(in.beta); + defer beta.free(); + var y = try t.alloc(sh.length * sh.value_heads * d * 4); + defer y.free(); + var state = try t.upload(in.state); + defer state.free(); + try run(t, sh, q, k, v, gate, beta, state, y, 0, sh.length); + try t.stream.synchronize(); + const wy = try rig.download(f32, y); + defer gpa.free(wy); + const ws = try rig.download(f32, state); + defer gpa.free(ws); + for ([_]usize{ 1, 63, 64, 65, 136 }) |c| { + try state.upload(0, std.mem.sliceAsBytes(in.state)); + try y.fill8(0); + try run(t, sh, q, k, v, gate, beta, state, y, 0, c); + try run(t, sh, q, k, v, gate, beta, state, y, c, sh.length - c); + try t.stream.synchronize(); + const gy = try rig.download(f32, y); + defer gpa.free(gy); + const gs = try rig.download(f32, state); + defer gpa.free(gs); + try std.testing.expectEqualSlices(u32, @ptrCast(wy), @ptrCast(gy)); + try std.testing.expectEqualSlices(u32, @ptrCast(ws), @ptrCast(gs)); + } +} diff --git a/zig/src/hip/kernel_tests/ops.zig b/zig/src/hip/kernel_tests/ops.zig new file mode 100644 index 00000000000..3556bbb1387 --- /dev/null +++ b/zig/src/hip/kernel_tests/ops.zig @@ -0,0 +1,513 @@ +//! Elementwise, rotation, gate, draw and routing kernels against host references, exact or within one rounding. +const std = @import("std"); +const rig = @import("rig.zig"); +const Rig = rig.Rig; +const gpa = rig.gpa; +const at = rig.at; +const ops = @import("../ops/ops.zig"); +const Tensor = ops.Tensor; +const Kind = ops.Kind; + +fn act(t: *const Rig) Kind { + return if (t.bf16) .bf16 else .f16; +} + +/// The activation's round-to-nearest-even of `v`, as torch rounds. +fn round(t: *const Rig, v: f64) u16 { + const f: f32 = @floatCast(v); + if (!t.bf16) return rig.f16Bits(f); + const u: u32 = @bitCast(f); + if (std.math.isNan(f)) return 0x7fc0; + return @intCast((u + 0x7fff + ((u >> 16) & 1)) >> 16); +} + +fn tensor(b: anytype, kind: Kind) Tensor { + return .{ .ptr = at(b), .kind = kind }; +} + +/// Within `ulps` units in the last place of the activation type, relative to the value's own size. +fn close(t: *const Rig, got: u16, want: f64, ulps: f64) bool { + return closeBy(t, got, want, ulps, 0); +} + +/// `close` with `slack` more: what a rotation may move when powf and the host's pow differ by an ulp. +fn closeBy(t: *const Rig, got: u16, want: f64, ulps: f64, slack: f64) bool { + const step: f64 = if (t.bf16) 1.0 / 128.0 else 1.0 / 1024.0; + return @abs(t.value(got) - want) <= ulps * step * @max(@abs(want), 1e-3) + slack; +} + +test "casts, sums, column copies and cache writes give torch's bits" { + const t = try Rig.open(1 << 20); + defer t.close(); + const o = t.ops(&t.on); + var rng: rig.Rng = .{ .state = 0xCA57 }; + const n = 4099; + const hf = try gpa.alloc(f32, n); + defer gpa.free(hf); + for (hf) |*x| x.* = @floatCast(rng.normal() * 3.7); + var f = try t.upload(hf); + defer f.free(); + var a = try t.alloc(n * 2); + defer a.free(); + try o.cast(tensor(f, .f32), tensor(a, act(t)), n); + var back = try t.alloc(n * 4); + defer back.free(); + try o.cast(tensor(a, act(t)), tensor(back, .f32), n); + const hy = try gpa.alloc(u16, n); + defer gpa.free(hy); + for (hy) |*x| x.* = t.bits(rng.unit()); + var y = try t.upload(hy); + defer y.free(); + var sum = try t.alloc(n * 2); + defer sum.free(); + try o.add(tensor(a, act(t)), tensor(y, act(t)), tensor(sum, act(t)), n); + try t.stream.synchronize(); + const ga = try rig.download(u16, a); + defer gpa.free(ga); + const gb = try rig.download(f32, back); + defer gpa.free(gb); + const gs = try rig.download(u16, sum); + defer gpa.free(gs); + for (hf, ga, gb, hy, gs) |x, rounded, widened, other, s| { + try std.testing.expectEqual(round(t, x), rounded); + try std.testing.expectEqual(@as(f32, @floatCast(t.value(rounded))), widened); + try std.testing.expectEqual(round(t, @as(f32, @floatCast(t.value(rounded))) + @as(f32, @floatCast(t.value(other)))), s); + } + + // columns [5, 105) of 7 rows of 300, then rows into a 3-head cache at slot 11, from the host and the device + var cols = try t.alloc(7 * 100 * 2); + defer cols.free(); + try o.copyCols(tensor(y, act(t)), 300, 5, at(cols), 7, 100); + const kv_heads = 3; + const d = 20; + const len = 4; + const total = 32; + var caches: [2]@import("../memory.zig").DeviceBuffer = .{ try t.alloc(kv_heads * total * d * 2), try t.alloc(kv_heads * total * d * 2) }; + defer for (&caches) |*c| c.free(); + for (&caches) |*c| try c.fill8(0); + try o.kvWrite(tensor(y, act(t)), at(caches[0]), len, kv_heads, d, total, 11); + const slot = [_]i32{11}; + var dev_slot = try t.upload(&slot); + defer dev_slot.free(); + try o.kvWriteAt(tensor(y, act(t)), at(caches[1]), len, kv_heads, d, total, at(dev_slot)); + try t.stream.synchronize(); + const gc = try rig.download(u16, cols); + defer gpa.free(gc); + for (0..7) |r| try std.testing.expectEqualSlices(u16, hy[r * 300 + 5 ..][0..100], gc[r * 100 ..][0..100]); + for (caches) |c| { + const gk = try rig.download(u16, c); + defer gpa.free(gk); + for (0..kv_heads) |h| for (0..total) |p| for (0..d) |j| { + const want: u16 = if (p >= 11 and p < 11 + len) hy[((p - 11) * kv_heads + h) * d + j] else 0; + try std.testing.expectEqual(want, gk[(h * total + p) * d + j]); + }; + } +} + +test "argmax and top-k follow torch's order: the larger value, then the lower index" { + const t = try Rig.open(1 << 20); + defer t.close(); + const o = t.ops(&t.on); + var rng: rig.Rng = .{ .state = 0xA4C }; + const rows = 5; + const n = 3001; + const hl = try gpa.alloc(u16, rows * n); + defer gpa.free(hl); + for (hl) |*x| x.* = t.bits(rng.unit() * 8.0); + // ties: row 1's top value twice, row 3's at both ends + hl[1 * n + 7] = t.bits(9.0); + hl[1 * n + 2000] = t.bits(9.0); + hl[3 * n + 0] = t.bits(9.5); + hl[3 * n + n - 1] = t.bits(9.5); + var logits = try t.upload(hl); + defer logits.free(); + var arg = try t.alloc(rows * 4); + defer arg.free(); + try o.argmaxRows(tensor(logits, act(t)), rows, n, at(arg)); + const ks = [_]i32{ 1, 8, 0, 40, 3 }; + const stride = 40; + var dev_ks = try t.upload(&ks); + defer dev_ks.free(); + var ids = try t.alloc(rows * stride * 4); + defer ids.free(); + var vals = try t.alloc(rows * stride * 2); + defer vals.free(); + try ids.fill8(0xff); + try o.topkRows(tensor(logits, act(t)), rows, n, at(dev_ks), stride, at(ids), at(vals)); + try t.stream.synchronize(); + const ga = try rig.download(i32, arg); + defer gpa.free(ga); + const gi = try rig.download(i32, ids); + defer gpa.free(gi); + const gv = try rig.download(u16, vals); + defer gpa.free(gv); + const order = try gpa.alloc(usize, n); + defer gpa.free(order); + for (0..rows) |r| { + const row = hl[r * n ..][0..n]; + for (order, 0..) |*x, i| x.* = i; + const Ctx = struct { + t: *const Rig, + row: []const u16, + fn before(c: @This(), a: usize, b: usize) bool { + const va = c.t.value(c.row[a]); + const vb = c.t.value(c.row[b]); + return va > vb or (va == vb and a < b); + } + }; + std.mem.sort(usize, order, Ctx{ .t = t, .row = row }, Ctx.before); + try std.testing.expectEqual(@as(i32, @intCast(order[0])), ga[r]); + // the k chosen by (value desc, id asc), each with its value; the kernel writes them in its own order + const k: usize = @intCast(ks[r]); + const got = gi[r * stride ..][0..k]; + for (got, gv[r * stride ..][0..k]) |id, v| try std.testing.expectEqual(row[@intCast(id)], v); + const chosen = try gpa.alloc(i32, k); + defer gpa.free(chosen); + for (chosen, order[0..k]) |*c, i| c.* = @intCast(i); + const sorted = try gpa.dupe(i32, got); + defer gpa.free(sorted); + std.mem.sort(i32, sorted, {}, std.sort.asc(i32)); + std.mem.sort(i32, chosen, {}, std.sort.asc(i32)); + try std.testing.expectEqualSlices(i32, chosen, sorted); + } + try std.testing.expectEqual(@as(i32, 7), ga[1]); + try std.testing.expectEqual(@as(i32, 0), ga[3]); + // k = 0 leaves the row untouched + try std.testing.expectEqual(@as(i32, -1), gi[2 * stride]); +} + +test "the MoE route sorts pairs by expert, stably, into items of at most a tile" { + const t = try Rig.open(1 << 20); + defer t.close(); + const o = t.ops(&t.on); + var rng: rig.Rng = .{ .state = 0x2017E }; + for ([_][3]usize{ .{ 257, 512, 16 }, .{ 128, 37, 4 }, .{ 64, 1000, 64 } }) |shape| { + const experts = shape[0]; + const pairs = shape[1]; + const tile = shape[2]; + const picks = try gpa.alloc(i32, pairs); + defer gpa.free(picks); + // a skewed pick so some experts fill several tiles and others none + for (picks) |*p| p.* = @intCast(@min(experts - 1, (rng.next() >> 40) % 16 * (rng.next() >> 50) % experts)); + const counts = try gpa.alloc(usize, experts); + defer gpa.free(counts); + @memset(counts, 0); + for (picks) |p| counts[@intCast(p)] += 1; + var capacity: usize = 0; + for (counts) |c| capacity += (c + tile - 1) / tile; + capacity += 3; + var dev_picks = try t.upload(picks); + defer dev_picks.free(); + var members = try t.alloc(pairs * 4); + defer members.free(); + var items = try t.alloc(capacity * 12); + defer items.free(); + try o.moeRoute(at(dev_picks), pairs, experts, tile, at(members), at(items), capacity); + try t.stream.synchronize(); + const gm = try rig.download(i32, members); + defer gpa.free(gm); + const gi = try rig.download(i32, items); + defer gpa.free(gi); + var place: usize = 0; + var slot: usize = 0; + for (0..experts) |e| { + const start = place; + for (picks, 0..) |p, i| if (p == e) { + try std.testing.expectEqual(@as(i32, @intCast(i)), gm[place]); + place += 1; + }; + var left = counts[e]; + var first = start; + while (left > 0) : (slot += 1) { + const take = @min(left, tile); + try std.testing.expectEqualSlices(i32, &.{ @intCast(e), @intCast(first), @intCast(take) }, gi[slot * 3 ..][0..3]); + first += take; + left -= take; + } + } + // the slots past the plan are empty items + for (slot..capacity) |s| try std.testing.expectEqual(@as(i32, 0), gi[s * 3 + 2]); + } +} + +fn silu(x: f64) f64 { + return x / (1 + @exp(-x)); +} + +fn sigmoid(x: f64) f64 { + return 1 / (1 + @exp(-x)); +} + +test "silu products, attention gates and the MoE activation sit within one rounding of float64" { + const t = try Rig.open(1 << 20); + defer t.close(); + const o = t.ops(&t.on); + var rng: rig.Rng = .{ .state = 0x51E }; + const n = 2048; + const hg = try gpa.alloc(u16, n); + defer gpa.free(hg); + const hu = try gpa.alloc(u16, n); + defer gpa.free(hu); + for (hg, hu) |*g, *u| { + g.* = t.bits(rng.unit() * 6); + u.* = t.bits(rng.unit() * 2); + } + var g = try t.upload(hg); + defer g.free(); + var u = try t.upload(hu); + defer u.free(); + var out = try t.alloc(n * 2); + defer out.free(); + try o.siluMul(tensor(g, act(t)), tensor(u, act(t)), tensor(out, act(t)), n); + // the gate: out[r, h * d + j] = att * sigmoid(qg's second half), att as (heads, len, d) + const len = 4; + const heads = 8; + const d = 64; + const hatt = try gpa.alloc(f32, len * heads * d); + defer gpa.free(hatt); + for (hatt) |*x| x.* = rng.unit(); + const hqg = try gpa.alloc(u16, len * heads * 2 * d); + defer gpa.free(hqg); + for (hqg) |*x| x.* = t.bits(rng.unit() * 4); + var att = try t.upload(hatt); + defer att.free(); + var qg = try t.upload(hqg); + defer qg.free(); + var gated = try t.alloc(len * heads * d * 2); + defer gated.free(); + try o.attnGate(at(att), tensor(qg, act(t)), tensor(gated, act(t)), len, heads, d, false); + // the MoE activation: silu(min(g, limit)) * clamp(u, -limit, limit), both halves fp32 + const pairs = 6; + const width = 96; + const hboth = try gpa.alloc(f32, pairs * 2 * width); + defer gpa.free(hboth); + for (hboth) |*x| x.* = rng.unit() * 10; + var both = try t.upload(hboth); + defer both.free(); + var moe = try t.alloc(pairs * width * 2); + defer moe.free(); + const limit: f32 = 7; + try o.moeAct(at(both), tensor(moe, act(t)), pairs, width, limit); + try t.stream.synchronize(); + const go = try rig.download(u16, out); + defer gpa.free(go); + for (hg, hu, go) |gv, uv, got| { + const s = t.value(round(t, silu(t.value(gv)))); + try std.testing.expect(close(t, got, s * t.value(uv), 1)); + } + const gg = try rig.download(u16, gated); + defer gpa.free(gg); + for (0..len) |r| for (0..heads) |h| for (0..d) |j| { + const want = @as(f64, hatt[(h * len + r) * d + j]) * sigmoid(t.value(hqg[(r * heads + h) * 2 * d + d + j])); + try std.testing.expect(close(t, gg[(r * heads + h) * d + j], want, 1)); + }; + const gm = try rig.download(u16, moe); + defer gpa.free(gm); + for (0..pairs) |p| for (0..width) |c| { + const gv = @min(@as(f64, hboth[p * 2 * width + c]), limit); + const uv = std.math.clamp(@as(f64, hboth[p * 2 * width + width + c]), -limit, limit); + try std.testing.expect(close(t, gm[p * width + c], silu(gv) * uv, 1)); + }; +} + +/// How far a rotated value may move when powf is one ulp from the host's pow: the angle moves by pos * 2^-23. +fn angleSlack(pos: usize, x1: f64, x2: f64) f64 { + return @as(f64, @floatFromInt(pos)) * 0x1p-23 * (@abs(x1) + @abs(x2)); +} + +/// torch's rotation of one pair at position `pos`, in f32 as the kernel and torch compute the angle. +fn rotation(i: usize, half: usize, pos: usize, theta: f32) [2]f64 { + const freq: f32 = 1.0 / std.math.pow(f32, theta, @as(f32, @floatFromInt(i)) / @as(f32, @floatFromInt(half))); + const ang: f32 = @as(f32, @floatFromInt(pos)) * freq; + return .{ @cos(@as(f64, ang)), @sin(@as(f64, ang)) }; +} + +test "RoPE for a prompt, a decode row and the fused q / k norm rotate within one rounding of float64" { + const t = try Rig.open(1 << 20); + defer t.close(); + const o = t.ops(&t.on); + var rng: rig.Rng = .{ .state = 0x20BE }; + const theta: f32 = 10_000_000; + const len = 5; + const heads = 4; + const d = 256; + const rotary = 64; + const half = rotary / 2; + const pos0 = 1000; + const hx = try gpa.alloc(u16, len * heads * d); + defer gpa.free(hx); + for (hx) |*x| x.* = t.bits(rng.unit() * 2); + var x = try t.upload(hx); + defer x.free(); + // the prompt's rotation, written (heads, len, d) + var out = try t.alloc(len * heads * d * 2); + defer out.free(); + try o.ropePrefill(tensor(x, act(t)), tensor(out, act(t)), len * d, d, len, heads, d, rotary, pos0, theta); + // a decode row: fp32 in and out, its position from the device + const hf = try gpa.alloc(f32, 3 * d); + defer gpa.free(hf); + for (hf) |*v| v.* = rng.unit(); + var f = try t.upload(hf); + defer f.free(); + var fy = try t.alloc(3 * d * 4); + defer fy.free(); + const positions = [_]i32{ 7, 70000, 123 }; + var dev_pos = try t.upload(&positions); + defer dev_pos.free(); + try o.ropeDecode(at(f), at(fy), 3, d, rotary, 0, theta, at(dev_pos), 1); + // the fused path: rms norm with a weight, then the rotation at each row's device position, into a cache + const hw = try gpa.alloc(f32, d); + defer gpa.free(hw); + for (hw) |*v| v.* = 1 + rng.unit() / 4; + var w = try t.upload(hw); + defer w.free(); + const total = 80000; + const qk_rows = 3; + var cache = try t.alloc(heads * total * d * 2); + defer cache.free(); + try o.qkRope(tensor(x, act(t)), heads * d, d, at(w), 1e-6, qk_rows, heads, d, rotary, theta, at(dev_pos), null, at(cache), total); + try t.stream.synchronize(); + const go = try rig.download(u16, out); + defer gpa.free(go); + for (0..len) |r| for (0..heads) |h| for (0..d) |j| { + const base = (r * heads + h) * d; + var want: f64 = t.value(hx[base + j]); + var slack: f64 = 0; + if (j < rotary) { + const i = if (j < half) j else j - half; + const cs = rotation(i, half, pos0 + r, theta); + const x1 = t.value(hx[base + i]); + const x2 = t.value(hx[base + i + half]); + want = if (j < half) x1 * cs[0] - x2 * cs[1] else x1 * cs[1] + x2 * cs[0]; + slack = angleSlack(pos0 + r, x1, x2); + } + try std.testing.expect(closeBy(t, go[(h * len + r) * d + j], want, 2, slack)); + }; + const gf = try rig.download(f32, fy); + defer gpa.free(gf); + for (0..3) |r| for (0..d) |j| { + const row = hf[r * d ..][0..d]; + var want: f64 = row[j]; + if (j < rotary) { + const i = if (j < half) j else j - half; + const cs = rotation(i, half, @intCast(positions[r]), theta); + want = if (j < half) row[i] * cs[0] - row[i + half] * cs[1] else row[i] * cs[1] + row[i + half] * cs[0]; + } + const i = if (j < half) j else if (j < rotary) j - half else j; + const slack = if (j < rotary) angleSlack(@intCast(positions[r]), row[i], row[@min(i + half, d - 1)]) else 0; + try std.testing.expect(@abs(gf[r * d + j] - want) < 1e-6 + slack); + }; + const gc = try gpa.alloc(u16, d); + defer gpa.free(gc); + for (0..qk_rows) |r| for (0..heads) |h| { + const p: usize = @intCast(positions[r]); + try cache.download(((h * total + p) * d) * 2, std.mem.sliceAsBytes(gc)); + const src = hx[(r * heads + h) * d ..][0..d]; + var ss: f64 = 0; + for (src) |v| ss += t.value(v) * t.value(v); + const inv = 1 / @sqrt(ss / d + 1e-6); + for (0..d) |j| { + const normed = struct { + fn of(tt: *const Rig, s: []const u16, weight: []const f32, k: usize, scale: f64) f64 { + return tt.value(round(tt, tt.value(s[k]) * scale * weight[k])); + } + }.of; + var want = normed(t, src, hw, j, inv); + var slack: f64 = 0; + if (j < rotary) { + const i = if (j < half) j else j - half; + const cs = rotation(i, half, p, theta); + const x1 = normed(t, src, hw, i, inv); + const x2 = normed(t, src, hw, i + half, inv); + want = if (j < half) x1 * cs[0] - x2 * cs[1] else x1 * cs[1] + x2 * cs[0]; + slack = angleSlack(p, x1, x2); + } + try std.testing.expect(closeBy(t, gc[j], want, 3, slack)); + } + }; +} + +test "the linear attention's prompt conv and DeltaNet gates sit within 1e-5 of float64" { + const t = try Rig.open(1 << 20); + defer t.close(); + const o = t.ops(&t.on); + var rng: rig.Rng = .{ .state = 0xC0417 }; + const len = 37; + const channels = 300; + const kernel = 4; + const kept = kernel - 1; + const hx = try gpa.alloc(u16, len * channels); + defer gpa.free(hx); + for (hx) |*x| x.* = t.bits(rng.unit() * 2); + const hw = try gpa.alloc(f32, channels * kernel); + defer gpa.free(hw); + for (hw) |*x| x.* = rng.unit() / 2; + const hs = try gpa.alloc(f32, kept * channels); + defer gpa.free(hs); + for (hs) |*x| x.* = rng.unit(); + var x = try t.upload(hx); + defer x.free(); + var w = try t.upload(hw); + defer w.free(); + var state = try t.upload(hs); + defer state.free(); + var out = try t.alloc(len * channels * 4); + defer out.free(); + var next = try t.alloc(kept * channels * 4); + defer next.free(); + try o.convPrefill(tensor(x, act(t)), at(w), at(state), at(out), at(next), len, channels, kernel); + const count = 9; + const heads = 32; + const ha = try gpa.alloc(u16, count * heads); + defer gpa.free(ha); + const hb = try gpa.alloc(u16, count * heads); + defer gpa.free(hb); + for (ha, hb) |*a, *b| { + a.* = t.bits(rng.unit() * 6); + b.* = t.bits(rng.unit() * 4); + } + const hlog = try gpa.alloc(f32, 2 * heads); + defer gpa.free(hlog); + for (hlog) |*v| v.* = rng.unit(); + var a = try t.upload(ha); + defer a.free(); + var b = try t.upload(hb); + defer b.free(); + var logs = try t.upload(hlog); + defer logs.free(); + var gate = try t.alloc(count * heads * 4); + defer gate.free(); + var beta = try t.alloc(count * heads * 4); + defer beta.free(); + try o.gdnGatePrefill(tensor(a, act(t)), tensor(b, act(t)), at(logs), at(logs) + heads * 4, at(gate), at(beta), count, heads); + try t.stream.synchronize(); + const go = try rig.download(f32, out); + defer gpa.free(go); + const gn = try rig.download(f32, next); + defer gpa.free(gn); + for (0..channels) |c| { + const window = struct { + fn at_(tt: *const Rig, xs: []const u16, ss: []const f32, ch: usize, n_ch: usize, k: usize, kp: usize) f64 { + return if (k < kp) ss[k * n_ch + ch] else tt.value(xs[(k - kp) * n_ch + ch]); + } + }.at_; + for (0..len) |r| { + var acc: f64 = 0; + for (0..kernel) |tap| acc += window(t, hx, hs, c, channels, r + tap, kept) * hw[c * kernel + tap]; + try std.testing.expect(@abs(go[r * channels + c] - silu(acc)) < 1e-5); + } + for (0..kept) |k| try std.testing.expectEqual(@as(f32, @floatCast(window(t, hx, hs, c, channels, len + k, kept))), gn[k * channels + c]); + } + const gg = try rig.download(f32, gate); + defer gpa.free(gg); + const gb = try rig.download(f32, beta); + defer gpa.free(gb); + for (0..count * heads) |i| { + const h = i % heads; + const xv = t.value(ha[i]) + hlog[heads + h]; + const sp = if (xv > 20) xv else @log(1 + @exp(xv)); + const want_gate = @exp(-@exp(@as(f64, hlog[h])) * sp); + try std.testing.expect(@abs(gg[i] - want_gate) <= 1e-5 * @max(want_gate, 1e-3)); + try std.testing.expect(@abs(gb[i] - sigmoid(t.value(hb[i]))) < 1e-6); + } +} diff --git a/zig/src/hip/kernel_tests/rig.zig b/zig/src/hip/kernel_tests/rig.zig new file mode 100644 index 00000000000..b6f659f8fd3 --- /dev/null +++ b/zig/src/hip/kernel_tests/rig.zig @@ -0,0 +1,176 @@ +//! What the kernel tests share: the device, a launcher with every choice on and one with each off, and helpers. +const std = @import("std"); +const Runtime = @import("../runtime.zig").Runtime; +const Context = @import("../context.zig").Context; +const Stream = @import("../stream.zig").Stream; +const DeviceBuffer = @import("../memory.zig").DeviceBuffer; +const Arena = @import("../arena.zig").Arena; +const Launcher = @import("../launches.zig").Launcher; +const Ops = @import("../ops/ops.zig").Ops; +const kernels = @import("../kernels.zig"); +const caps = @import("../caps.zig"); + +pub const gpa = std.testing.allocator; + +pub const Rng = struct { + state: u64, + + pub fn next(r: *Rng) u64 { + r.state ^= r.state >> 12; + r.state ^= r.state << 25; + r.state ^= r.state >> 27; + return r.state *% 0x2545F4914F6CDD1D; + } + + /// Uniform on [-1, 1) in 1/1024 steps. + pub fn unit(r: *Rng) f32 { + const v: i32 = @intCast(r.next() >> 40 & 0x7ff); + return @as(f32, @floatFromInt(v - 1024)) / 1024.0; + } + + pub fn uniform(r: *Rng) f64 { + return (@as(f64, @floatFromInt(r.next() >> 11)) + 0.5) / 9007199254740992.0; + } + + pub fn normal(r: *Rng) f64 { + const a = r.uniform(); + const b = r.uniform(); + return @sqrt(-2 * @log(a)) * @cos(2 * std.math.pi * b); + } +}; + +pub const Rig = struct { + r: Runtime, + ctx: Context, + stream: Stream, + /// Every kernel choice on, as a run takes them. + on: Launcher, + /// Merged decode launches off: the kernels they replace. + off: Launcher, + arena: Arena, + /// The activation type: bf16 where the GPU has a bf16 dot2, fp16 on RDNA2. + bf16: bool, + + pub fn open(arena_bytes: usize) !*Rig { + const t = try gpa.create(Rig); + errdefer gpa.destroy(t); + t.r = try Runtime.open(); + errdefer t.r.close(); + t.ctx = try Context.init(&t.r, 0); + errdefer t.ctx.deinit(); + t.stream = try Stream.init(&t.r); + errdefer t.stream.deinit(); + t.on = try Launcher.load(&t.r, .{}, kernels.images); + errdefer t.on.unload(); + t.off = try Launcher.load(&t.r, .{ .fuse = false }, kernels.images); + errdefer t.off.unload(); + t.arena = try Arena.init(&t.r, arena_bytes); + t.bf16 = caps.Caps.of(kernels.arch).?.act == .bf16; + return t; + } + + pub fn close(t: *Rig) void { + t.arena.deinit(); + t.off.unload(); + t.on.unload(); + t.stream.deinit(); + t.ctx.deinit(); + t.r.close(); + gpa.destroy(t); + } + + pub fn ops(t: *Rig, l: *const Launcher) Ops { + return .{ .l = l, .bf16 = t.bf16, .stream = t.stream.handle, .arena = &t.arena }; + } + + pub fn upload(t: *Rig, host: anytype) !DeviceBuffer { + return DeviceBuffer.fromHost(&t.r, std.mem.sliceAsBytes(host)); + } + + pub fn alloc(t: *Rig, bytes: usize) !DeviceBuffer { + return DeviceBuffer.alloc(&t.r, bytes); + } + + /// The activation's 16-bit pattern of `v` and its value. + pub fn bits(t: *const Rig, v: f32) u16 { + return if (t.bf16) bf16Bits(v) else f16Bits(v); + } + + pub fn value(t: *const Rig, b: u16) f64 { + return if (t.bf16) bf16Value(b) else f16Value(b); + } + + /// The activation kind as the kernels number it: 1 fp16, 2 bf16. + pub fn kind(t: *const Rig) c_int { + return if (t.bf16) 2 else 1; + } +}; + +pub fn at(b: DeviceBuffer) u64 { + return @intFromPtr(b.ptr); +} + +pub fn download(comptime T: type, b: DeviceBuffer) ![]T { + const out = try gpa.alloc(T, b.len / @sizeOf(T)); + errdefer gpa.free(out); + try b.download(0, std.mem.sliceAsBytes(out)); + return out; +} + +pub fn f16Bits(v: f32) u16 { + const h: f16 = @floatCast(v); + return @bitCast(h); +} + +pub fn f16Value(b: u16) f64 { + const h: f16 = @bitCast(b); + return h; +} + +/// bf16 by truncation: test inputs are chosen exact in bf16. +pub fn bf16Bits(v: f32) u16 { + return @intCast(@as(u32, @bitCast(v)) >> 16); +} + +pub fn bf16Value(b: u16) f64 { + return @as(f32, @bitCast(@as(u32, b) << 16)); +} + +/// A device buffer with its address, as the product tests hand it to launches. +pub const Buffer = struct { + buf: DeviceBuffer, + ptr: u64, + + pub fn alloc(t: *Rig, bytes: usize) !Buffer { + const b = try DeviceBuffer.alloc(&t.r, bytes); + return .{ .buf = b, .ptr = at(b) }; + } + + pub fn fromHost(t: *Rig, host: anytype) !Buffer { + const b = try t.upload(host); + return .{ .buf = b, .ptr = at(b) }; + } + + pub fn free(b: *Buffer) void { + b.buf.free(); + } + + pub fn fill8(b: Buffer, value: u8, _: @TypeOf(null)) !void { + try b.buf.fill8(value); + } + + pub fn upload(b: Buffer, offset: usize, bytes: []const u8) !void { + try b.buf.upload(offset, bytes); + } + + pub fn download(b: Buffer, offset: usize, out: []u8) !void { + try b.buf.download(offset, out); + } +}; + +/// A failed check with its message. +pub fn expect(ok: bool, comptime fmt: []const u8, args: anytype) !void { + if (ok) return; + std.debug.print(fmt ++ "\n", args); + return error.TestUnexpectedResult; +} diff --git a/zig/src/hip/kernel_tests/tp.zig b/zig/src/hip/kernel_tests/tp.zig new file mode 100644 index 00000000000..dd1b80f1f73 --- /dev/null +++ b/zig/src/hip/kernel_tests/tp.zig @@ -0,0 +1,128 @@ +//! A tensor-parallel rank's kernels and MTP's token probability against host references. +const std = @import("std"); +const rig = @import("rig.zig"); +const Rig = rig.Rig; +const gpa = rig.gpa; +const at = rig.at; +const ops = @import("../ops/ops.zig"); +const Kind = ops.Kind; + +fn act(t: *const Rig) Kind { + return if (t.bf16) .bf16 else .f16; +} + +/// The activation's round-to-nearest-even of an fp32 value, as torch rounds. +fn round(t: *const Rig, f: f32) u16 { + if (!t.bf16) return rig.f16Bits(f); + const u: u32 = @bitCast(f); + if (std.math.isNan(f)) return 0x7fc0; + return @intCast((u + 0x7fff + ((u >> 16) & 1)) >> 16); +} + +test "a residual plus an fp32 sum rounds once to the activation, and the expert-share remap and masks are exact" { + const t = try Rig.open(1 << 20); + defer t.close(); + const o = t.ops(&t.on); + var rng: rig.Rng = .{ .state = 0x7B }; + const n = 3000; + const hx = try gpa.alloc(u16, n); + defer gpa.free(hx); + const hy = try gpa.alloc(f32, n); + defer gpa.free(hy); + for (hx, hy) |*x, *y| { + x.* = t.bits(rng.unit() * 6.0 - 3.0); + y.* = rng.unit() * 0.01 - 0.005; + } + var x = try t.upload(hx); + defer x.free(); + var y = try t.upload(hy); + defer y.free(); + var out = try t.alloc(n * 2); + defer out.free(); + try o.addWide(.{ .ptr = at(x), .kind = act(t) }, at(y), .{ .ptr = at(out), .kind = act(t) }, n); + const experts = 16; + const skip = 8; + var remap: [experts]i32 = undefined; + for (&remap, 0..) |*r, e| r.* = if (e % 2 == 0) @intCast(e / 2) else -1; + var picks: [64]i32 = undefined; + for (&picks) |*p| p.* = @intCast(rng.next() % experts); + var dev_remap = try t.upload(&remap); + defer dev_remap.free(); + var dev_picks = try t.upload(&picks); + defer dev_picks.free(); + var local = try t.alloc(picks.len * 4); + defer local.free(); + try o.moeLocalize(at(dev_picks), at(dev_remap), at(local), picks.len, skip); + var items = [_]i32{ 0, 0, 5, skip, 5, 7, 3, 12, 2, skip, 17, 1 }; + var dev_items = try t.upload(&items); + defer dev_items.free(); + try o.moeForeignItems(at(dev_items), items.len / 3, skip); + const d = 33; + const ys = try gpa.alloc(f32, picks.len * d); + defer gpa.free(ys); + for (ys) |*v| v.* = rng.unit() + 1.0; + var dev_ys = try t.upload(ys); + defer dev_ys.free(); + var local_picks: [picks.len]i32 = undefined; + for (&local_picks, picks) |*l, p| l.* = if (remap[@intCast(p)] >= 0) remap[@intCast(p)] else skip; + var dev_local = try t.upload(&local_picks); + defer dev_local.free(); + try o.moeZeroForeign(at(dev_ys), at(dev_local), skip, picks.len, d); + try t.stream.synchronize(); + const got = try rig.download(u16, out); + defer gpa.free(got); + for (got, hx, hy) |g, xb, yv| try std.testing.expectEqual(round(t, @as(f32, @floatCast(t.value(xb))) + yv), g); + const gl = try rig.download(i32, local); + defer gpa.free(gl); + try std.testing.expectEqualSlices(i32, &local_picks, gl); + const gi = try rig.download(i32, dev_items); + defer gpa.free(gi); + for (0..items.len / 3) |k| { + const want: i32 = if (items[3 * k] == skip) 0 else items[3 * k + 2]; + try std.testing.expectEqual(items[3 * k], gi[3 * k]); + try std.testing.expectEqual(want, gi[3 * k + 2]); + } + const gy = try rig.download(f32, dev_ys); + defer gpa.free(gy); + for (gy, ys, 0..) |g, v, k| try std.testing.expectEqual(if (local_picks[k / d] == skip) 0 else v, g); +} + +test "a token's probability is its softmax share of the row, or the largest one's with no ids, within 1e-6 of float64" { + const t = try Rig.open(1 << 20); + defer t.close(); + const o = t.ops(&t.on); + var rng: rig.Rng = .{ .state = 0x9E1 }; + const rows = 6; + const n = 4099; + const hl = try gpa.alloc(u16, rows * n); + defer gpa.free(hl); + for (hl) |*x| x.* = t.bits(rng.unit() * 16.0 - 8.0); + var ids: [rows]i32 = undefined; + for (&ids) |*id| id.* = @intCast(rng.next() % n); + var logits = try t.upload(hl); + defer logits.free(); + var dev_ids = try t.upload(&ids); + defer dev_ids.free(); + var with_ids = try t.alloc(rows * 4); + defer with_ids.free(); + var largest = try t.alloc(rows * 4); + defer largest.free(); + const l: ops.Tensor = .{ .ptr = at(logits), .kind = act(t) }; + try o.tokenProb(l, rows, n, at(dev_ids), at(with_ids)); + try o.tokenProb(l, rows, n, 0, at(largest)); + try t.stream.synchronize(); + const gw = try rig.download(f32, with_ids); + defer gpa.free(gw); + const gm = try rig.download(f32, largest); + defer gpa.free(gm); + for (0..rows) |r| { + const row = hl[r * n ..][0..n]; + var peak: f64 = -std.math.inf(f64); + for (row) |x| peak = @max(peak, t.value(x)); + var total: f64 = 0; + for (row) |x| total += @exp(t.value(x) - peak); + const want = @exp(t.value(row[@intCast(ids[r])]) - peak) / total; + try std.testing.expectApproxEqAbs(want, gw[r], 1e-6); + try std.testing.expectApproxEqAbs(1.0 / total, gm[r], 1e-6); + } +} diff --git a/zig/src/hip/kernels.zig b/zig/src/hip/kernels.zig new file mode 100644 index 00000000000..fdc600f6c2a --- /dev/null +++ b/zig/src/hip/kernels.zig @@ -0,0 +1,12 @@ +//! The model-free kernels' code objects, built by hipcc for -Dhip-arch and embedded, one a source group. +const objects = @import("hip_kernels"); + +/// The source groups of zig/kernels/hip, in the order the build embeds them. +pub const Group = enum { ops, act, attention, gated_delta, prefill, decode, plan, affine_tiles, affine_dot2 }; +pub const group_count = @typeInfo(Group).@"enum".field_names.len; + +/// The architecture the objects were built for; the loader takes them only on that device. +pub const arch: []const u8 = objects.arch; + +/// The objects in `Group` order; empty in a build without hipcc. +pub const images: [group_count][]align(8) const u8 = objects.images; diff --git a/zig/src/hip/launches.zig b/zig/src/hip/launches.zig new file mode 100644 index 00000000000..a93b5b9ba80 --- /dev/null +++ b/zig/src/hip/launches.zig @@ -0,0 +1,337 @@ +//! The model-free kernels launched from Zig on the embedded code objects, one module a source group. + +const std = @import("std"); +const runtime = @import("runtime.zig"); +const kernels = @import("kernels.zig"); +const launch = @import("launch.zig"); +const Module = @import("module.zig").Module; +const Function = @import("module.zig").Function; +const Stream = @import("stream.zig").Stream; +const caps = @import("caps.zig"); +const affine = @import("launches/affine.zig"); + +const util = @import("launches/util.zig"); + +pub const Error = util.Error; + +const S = util.S; +const P = util.P; +const C = util.C; +const F = util.F; +const CF = util.CF; +const I = util.I; +const CI = util.CI; +const Dim3 = util.Dim3; +const Args = util.Args; +const Triple = util.Triple; +const ad = util.ad; +const dim = util.dim; +const cdiv = util.cdiv; + +const norms = @import("launches/norms.zig"); +const conv = @import("launches/conv.zig"); +const rope = @import("launches/rope.zig"); +const moe = @import("launches/moe.zig"); +const attention = @import("launches/attention.zig"); +const recurrence = @import("launches/recurrence.zig"); +const plan = @import("launches/plan.zig"); +const elementwise = @import("launches/elementwise.zig"); +const draw = @import("launches/draw.zig"); +const tp = @import("launches/tp.zig"); + +pub const ConvArgs = conv.ConvArgs; +pub const PlanArgs = plan.PlanArgs; +pub const PlanRef = plan.PlanRef; +pub const PlanKeep = plan.Keep; +pub const gdn_chunk = recurrence.gdn_chunk; + +pub const Launcher = struct { + r: *const runtime.Runtime, + mods: [kernels.group_count]Module, + rms: Triple, + conv_decode: Function, + conv_rows: Function, + rope_decode: Function, + moe_router: [2]Function, // fp16, bf16 + moe_select: Function, + moe_act: [2]Function, + moe_combine: Triple, + gdn_gate: Triple, + gated_delta_tile: [2]Function, // dk 128, 16 + gated_delta_wave: [2]Function, + score_keys: Triple, // by cache kind + apply_values: Triple, + causal: Triple, + fa_prefill: Triple, + fa_wide: [2]Function, // the 64-row prefill tile, fp16 and bf16 caches + fa_paged: [2]Function, // the same tile over a stream's pages + softmax_stats: Function, + sum_partials: Function, + op: Ops, + /// decode.hip's kernels: a round's few rows, and the launches that merge several small ones. + dec: Decode, + /// plan.hip's kernels and the DeltaNet's over a round's plan. + plan: PlanFns, + /// decode.hip's merged launches are on (off keeps the launches they replace). + fuse: bool, + /// The 64-row prefill attention tile is on. + wide: bool, + /// The MLX affine products and the registry that picks their tiles. + affine: affine.Kernels, + + const PlanFns = struct { + kv_write: Function, + score: [2]Function, // fp16, bf16 + apply: [2]Function, + keep: Function, + gather: Function, + gdn: [2]Function, // dk 128, 16 + gdn_replay: [2]Function, // dk 128, 16 + page_write: Function, + page_gather: Function, + }; + + const Decode = struct { + router: [2]Function, // fp16, bf16 + tail: Function, + conv_split: Function, + rms2: Function, + gnorm_out: Function, + select: Function, + }; + + const Ops = struct { + embed_rows: Function, + embed_dense: Function, + cast: Function, + silu_mul: Function, + add: Function, + attn_gate: Function, + gnorm_silu: Function, + copy_cols: Function, + rope_prefill: Function, + kv_write: Function, + kv_write_at: Function, + argmax: Function, + topk: Function, + conv_prefill: Function, + gdn_gate_prefill: Function, + dense_rows: Function, + moe_route: Function, + router_rows: [2]Function, // fp16, bf16 + router_tile: [2]Function, + router_small: [2]Function, + rms_rows: Function, + qk_rope: Function, + add_wide: Function, + moe_localize: Function, + moe_foreign_items: Function, + moe_zero_foreign: Function, + token_prob: Function, + }; + + /// Which kernels a run takes where two give the same bits; every one defaults on. + pub const Choices = struct { fuse: bool = true, wide: bool = true, products: affine.Choices = .{} }; + + /// Loads the code objects on the current device and resolves every kernel the launchers use. + pub fn load(r: *const runtime.Runtime, choices: Choices, images: [kernels.group_count][]align(8) const u8) Error!Launcher { + var l: Launcher = undefined; + l.r = r; + var loaded: usize = 0; + errdefer for (l.mods[0..loaded]) |*m| m.unload(); + for (images, 0..) |img, i| { + l.mods[i] = try Module.load(r, img); + loaded += 1; + } + const ops = l.mods[@backingInt(kernels.Group.ops)]; + const act = l.mods[@backingInt(kernels.Group.act)]; + const att = l.mods[@backingInt(kernels.Group.attention)]; + const gd = l.mods[@backingInt(kernels.Group.gated_delta)]; + const pre = l.mods[@backingInt(kernels.Group.prefill)]; + const dec = l.mods[@backingInt(kernels.Group.decode)]; + const pl = l.mods[@backingInt(kernels.Group.plan)]; + l.fuse = choices.fuse; + l.wide = choices.wide; + l.dec = .{ .router = .{ try dec.function("tf_router_decode_f16"), try dec.function("tf_router_decode_bf16") }, .tail = try dec.function("tf_tail"), .conv_split = try dec.function("tf_conv_split"), .rms2 = try dec.function("tf_rms2"), .gnorm_out = try dec.function("tf_gnorm_out"), .select = try dec.function("tf_select_decode") }; + l.plan = .{ + .kv_write = try pl.function("tf_plan_kv_write"), + .score = .{ try pl.function("tf_plan_score_f16"), try pl.function("tf_plan_score_bf16") }, + .apply = .{ try pl.function("tf_plan_apply_f16"), try pl.function("tf_plan_apply_bf16") }, + .keep = try pl.function("tf_plan_keep"), + .gather = try pl.function("tf_plan_gather"), + .gdn = .{ try gd.function("tf_gdn_plan_128"), try gd.function("tf_gdn_plan_16") }, + .gdn_replay = .{ try gd.function("tf_gdn_replay_128"), try gd.function("tf_gdn_replay_16") }, + .page_write = try pl.function("tf_page_write"), + .page_gather = try pl.function("tf_page_gather"), + }; + l.fa_wide = .{ try pre.function("tf_fa_wide_f16"), try pre.function("tf_fa_wide_bf16") }; + l.fa_paged = .{ try pre.function("tf_fa_paged_f16"), try pre.function("tf_fa_paged_bf16") }; + l.op = .{ + .embed_rows = try ops.function("tf_embed_rows"), + .embed_dense = try ops.function("tf_embed_dense"), + .cast = try ops.function("tf_cast"), + .silu_mul = try ops.function("tf_silu_mul"), + .add = try ops.function("tf_add"), + .attn_gate = try ops.function("tf_attn_gate"), + .gnorm_silu = try ops.function("tf_gnorm_silu"), + .copy_cols = try ops.function("tf_copy_cols"), + .rope_prefill = try ops.function("tf_rope_prefill"), + .kv_write = try ops.function("tf_kv_write"), + .kv_write_at = try ops.function("tf_kv_write_at"), + .argmax = try ops.function("tf_argmax"), + .topk = try ops.function("tf_topk"), + .conv_prefill = try ops.function("tf_conv_prefill"), + .gdn_gate_prefill = try ops.function("tf_gdn_gate_prefill"), + .dense_rows = try ops.function("tf_dense_rows"), + .moe_route = try ops.function("tf_moe_route"), + .router_rows = .{ try ops.function("tf_router_rows_f16"), try ops.function("tf_router_rows_bf16") }, + .router_tile = .{ try ops.function("tf_router_tile_f16"), try ops.function("tf_router_tile_bf16") }, + .router_small = .{ try ops.function("tf_router_small_f16"), try ops.function("tf_router_small_bf16") }, + .rms_rows = try ops.function("tf_rms_rows"), + .qk_rope = try ops.function("tf_qk_rope"), + .add_wide = try ops.function("tf_add_wide"), + .moe_localize = try ops.function("tf_moe_localize"), + .moe_foreign_items = try ops.function("tf_moe_foreign_items"), + .moe_zero_foreign = try ops.function("tf_moe_zero_foreign"), + .token_prob = try ops.function("tf_token_prob"), + }; + const ns = "_ZN2tf4rocm"; + l.rms = .{ + try act.function(ns ++ "10rms_kernelIfEEvPKT_PKfPS2_if"), + try act.function(ns ++ "10rms_kernelI6__halfEEvPKT_PKfPS3_if"), + try act.function(ns ++ "10rms_kernelI12hip_bfloat16EEvPKT_PKfPS3_if"), + }; + l.conv_decode = try act.function("tf_conv_decode"); + l.conv_rows = try act.function("tf_conv_rows"); + l.rope_decode = try act.function("tf_rope_decode"); + l.moe_router = .{ + try act.function(ns ++ "17moe_router_kernelI6__halfEEvPKT_PKfPfii"), + try act.function(ns ++ "17moe_router_kernelI12hip_bfloat16EEvPKT_PKfPfii"), + }; + l.moe_select = try act.function("tf_moe_select"); + l.moe_act = .{ + try act.function(ns ++ "14moe_act_kernelI6__halfEEvPKfPT_ifx"), + try act.function(ns ++ "14moe_act_kernelI12hip_bfloat16EEvPKfPT_ifx"), + }; + l.moe_combine = .{ + try act.function(ns ++ "18moe_combine_kernelIfEEvPKfS3_PT_ii"), + try act.function(ns ++ "18moe_combine_kernelI6__halfEEvPKfS4_PT_ii"), + try act.function(ns ++ "18moe_combine_kernelI12hip_bfloat16EEvPKfS4_PT_ii"), + }; + l.gdn_gate = .{ + try act.function(ns ++ "15gdn_gate_kernelIfEEvPKT_S4_PKfS6_PfS7_ii"), + try act.function(ns ++ "15gdn_gate_kernelI6__halfEEvPKT_S5_PKfS7_PfS8_ii"), + try act.function(ns ++ "15gdn_gate_kernelI12hip_bfloat16EEvPKT_S5_PKfS7_PfS8_ii"), + }; + l.gated_delta_tile = .{ + try gd.function(ns ++ "16gated_delta_tileILi128ELi8ELi16EEEvPKfS3_S3_S3_S3_PfS4_iiiiS4_"), + try gd.function(ns ++ "16gated_delta_tileILi16ELi8ELi16EEEvPKfS3_S3_S3_S3_PfS4_iiiiS4_"), + }; + l.gated_delta_wave = .{ + try gd.function(ns ++ "18gated_delta_kernelILi128EEEvPKfS3_S3_S3_S3_PfS4_iiiiS4_"), + try gd.function(ns ++ "18gated_delta_kernelILi16EEEvPKfS3_S3_S3_S3_PfS4_iiiiS4_"), + }; + l.score_keys = .{ + try att.function("_Z10score_keysI6__halfEvPKfPKT_PfiiiifixxxPKi"), + try att.function("_Z10score_keysI12hip_bfloat16EvPKfPKT_PfiiiifixxxPKi"), + try att.function("_Z10score_keysIfEvPKfPKT_PfiiiifixxxPKi"), + }; + l.apply_values = .{ + try att.function("_Z12apply_valuesI6__halfEvPKfS2_PKT_PfiiiiixxxPKi"), + try att.function("_Z12apply_valuesI12hip_bfloat16EvPKfS2_PKT_PfiiiiixxxPKi"), + try att.function("_Z12apply_valuesIfEvPKfS1_PKT_PfiiiiixxxPKi"), + }; + l.causal = .{ + try att.function(ns ++ "13causal_kernelI6__halfEEvPKfPKT_S7_Pfiiiiifixxxxxx"), + try att.function(ns ++ "13causal_kernelI12hip_bfloat16EEvPKfPKT_S7_Pfiiiiifixxxxxx"), + try att.function(ns ++ "13causal_kernelIfEEvPKfPKT_S6_Pfiiiiifixxxxxx"), + }; + l.fa_prefill = .{ + try att.function(ns ++ "10fa_prefillI6__halfLi64EEEvPKfPKT_S7_Pfiiiiifixxxxxx"), + try att.function(ns ++ "10fa_prefillI12hip_bfloat16Li64EEEvPKfPKT_S7_Pfiiiiifixxxxxx"), + try att.function(ns ++ "10fa_prefillIfLi32EEEvPKfPKT_S6_Pfiiiiifixxxxxx"), + }; + l.softmax_stats = try att.function("tf_softmax_stats"); + l.sum_partials = try att.function("tf_sum_partials"); + const tiles = l.mods[@backingInt(kernels.Group.affine_tiles)]; + const dot2 = l.mods[@backingInt(kernels.Group.affine_dot2)]; + l.affine = try affine.Kernels.load(tiles, dot2, caps.Caps.of(kernels.arch) orelse return error.Invalid, choices.products); + try l.affine.fillByteLut(r, dot2); + return l; + } + + pub fn unload(l: *Launcher) void { + for (&l.mods) |*m| m.unload(); + } + + pub const tf_rms = norms.tf_rms; + pub const tf_rms2 = norms.tf_rms2; + pub const tf_gnorm_out = norms.tf_gnorm_out; + pub const tf_tail = norms.tf_tail; + pub const tf_conv_decode = conv.tf_conv_decode; + pub const tf_conv_rows = conv.tf_conv_rows; + pub const tf_conv_split = conv.tf_conv_split; + pub const tf_conv_prefill = conv.tf_conv_prefill; + pub const tf_qk_rope = rope.tf_qk_rope; + pub const tf_rope_decode = rope.tf_rope_decode; + pub const tf_rope_prefill = rope.tf_rope_prefill; + pub const routerTile = moe.routerTile; + pub const routerWith = moe.routerWith; + pub const routerWindow = moe.routerWindow; + pub const tf_moe_router = moe.tf_moe_router; + pub const tf_moe_select = moe.tf_moe_select; + pub const tf_moe_act = moe.tf_moe_act; + pub const tf_moe_combine = moe.tf_moe_combine; + pub const tf_moe_route = moe.tf_moe_route; + pub const tf_causal = attention.tf_causal; + pub const tf_attn_gate = attention.tf_attn_gate; + pub const tf_kv_write = attention.tf_kv_write; + pub const tf_kv_write_at = attention.tf_kv_write_at; + pub const tf_argmax_rows = draw.tf_argmax_rows; + pub const tf_topk_rows = draw.tf_topk_rows; + pub const tf_add_wide = tp.tf_add_wide; + pub const tf_moe_localize = tp.tf_moe_localize; + pub const tf_moe_foreign_items = tp.tf_moe_foreign_items; + pub const tf_moe_zero_foreign = tp.tf_moe_zero_foreign; + pub const tf_token_prob = tp.tf_token_prob; + pub const pagedCausal = attention.pagedCausal; + pub const tf_gdn_gate = recurrence.tf_gdn_gate; + pub const tf_gated_delta = recurrence.tf_gated_delta; + pub const planKvWrite = plan.planKvWrite; + pub const planCausal = plan.planCausal; + pub const planGatedDelta = plan.planGatedDelta; + pub const planKeep = plan.planKeep; + pub const planGdnReplay = plan.planGdnReplay; + pub const pagesWrite = plan.pagesWrite; + pub const pagesGather = plan.pagesGather; + pub const planGather = plan.planGather; + pub const tf_gdn_gate_prefill = recurrence.tf_gdn_gate_prefill; + pub const tf_gnorm_silu = recurrence.tf_gnorm_silu; + pub const tf_embed_rows = elementwise.tf_embed_rows; + pub const tf_embed_dense = elementwise.tf_embed_dense; + pub const tf_cast = elementwise.tf_cast; + pub const tf_silu_mul = elementwise.tf_silu_mul; + pub const tf_add = elementwise.tf_add; + pub const tf_copy_cols = elementwise.tf_copy_cols; + pub const tf_dense_rows = elementwise.tf_dense_rows; + + /// Launches on `s`; the counting stream runs nothing. + pub fn go(l: *const Launcher, f: Function, grid: Dim3, block: Dim3, shared: u32, s: S, args: *Args) Error!void { + if (s == util.counting) return; + try launch.launch(f, .{ .grid = grid, .block = block, .shared = shared }, Stream{ .r = l.r, .handle = s }, args); + } + + pub fn tf_affine(l: *const Launcher, x: C, words: C, scale: C, bias: C, scale_kind: c_int, out: P, m: c_int, n: c_int, k: c_int, bits: c_int, group: c_int, schedule: c_int, fp16: c_int, s: S, partial: F, splits: c_int, out_half: c_int) Error!void { + try l.affine.run(l.r, .{ .x = ad(x), .words = ad(words), .scale = .{ .p = ad(scale), .kind = scale_kind }, .bias = .{ .p = ad(bias), .kind = scale_kind }, .out = ad(out), .m = m, .n = n, .k = k, .bits = bits, .group = group, .fp16 = fp16 }, schedule, s, ad(partial), splits, out_half != 0); + } + + pub fn tf_affine_routed(l: *const Launcher, x: C, words: C, scale: C, bias: C, scale_kind: c_int, out: P, items: CI, count: c_int, members: CI, x_div: c_int, rows: c_int, n: c_int, k: c_int, bits: c_int, group: c_int, fp16: c_int, s: S) Error!void { + try l.affine.routed(l.r, .{ .x = ad(x), .words = ad(words), .scale = .{ .p = ad(scale), .kind = scale_kind }, .bias = .{ .p = ad(bias), .kind = scale_kind }, .out = ad(out), .m = rows, .n = n, .k = k, .bits = bits, .group = group, .fp16 = fp16, .route = .{ .items = ad(items), .members = ad(members), .x_div = x_div } }, count, s); + } + + /// The 256-thread, one-element-a-thread launch of an ops.hip kernel over `n` elements. + pub fn flat(l: *const Launcher, f: Function, n: i64, s: S, a: *Args) Error!void { + if (n == 0) return; + try l.go(f, dim(cdiv(n, 256), 1, 1), dim(256, 1, 1), 0, s, a); + } +}; diff --git a/zig/src/hip/launches/affine.zig b/zig/src/hip/launches/affine.zig new file mode 100644 index 00000000000..7c2b8a0ccd2 --- /dev/null +++ b/zig/src/hip/launches/affine.zig @@ -0,0 +1,547 @@ +//! The MLX affine tiles of tiles/dot2_tiles.hip and tiles/dot2.hip launched from Zig; the registry picks one. + +const std = @import("std"); +const abi = @import("../abi.zig"); +const runtime = @import("../runtime.zig"); +const hl = @import("../launch.zig"); +const Module = @import("../module.zig").Module; +const Function = @import("../module.zig").Function; +const Stream = @import("../stream.zig").Stream; +const util = @import("util.zig"); + +const Caps = @import("../caps.zig").Caps; +const registry = @import("core").registry; +const quant = @import("core").quant; +const tuning = @import("../tuning/tuning.zig"); +const mlx_entries = @import("mlx_entries.zig"); + +const Error = runtime.Error; + +/// Matrix cores for products: `off` keeps every product on dot2 tiles; `auto` and `on` use them where a tile exists. +pub const Matrix = enum { auto, on, off }; + +/// Which product tiles a run takes where two give the same bits; every one defaults on. +pub const Choices = struct { matrix: Matrix = .auto, stream: bool = true, gemm: bool = true }; + +/// quant/mlx.hpp's GroupTable, Routing and Affine as the kernels take them by value. +pub const GroupTable = extern struct { p: u64, kind: c_int }; +pub const Routing = extern struct { items: u64 = 0, members: u64 = 0, x_div: c_int = 1, first: c_int = 0 }; +pub const Arg = extern struct { + x: u64, + words: u64, + scale: GroupTable, + bias: GroupTable, + out: u64, + m: c_int, + n: c_int, + k: c_int, + bits: c_int, + group: c_int, + fp16: c_int, + route: Routing = .{}, + out16: u64 = 0, +}; + +/// quant/mlx_tiles.hpp's StreamSides: up to four products that share x, K, width and group in one launch. +pub const StreamSides = extern struct { + words: [4]u64 = @splat(0), + scale: [4]u64 = @splat(0), + bias: [4]u64 = @splat(0), + out: [4]u64 = @splat(0), + n: [4]c_int = @splat(0), + first: [5]c_int = @splat(0), + count: c_int = 0, + out_half: c_int = 0, + pair_cols: c_int = 0, + limit: f32 = 0, +}; + +/// One side of a group: its matrix and where its (rows, n) output goes. +pub const Side = struct { words: u64, scale: u64, bias: u64, n: c_int, out: u64 }; + +comptime { + std.debug.assert(@sizeOf(GroupTable) == 16 and @sizeOf(Routing) == 24 and @sizeOf(Arg) == 112 and @sizeOf(StreamSides) == 184); +} + +/// Everything a launch needs beside the kernels. +pub const Call = struct { + r: *const runtime.Runtime, + s: abi.Stream, + arg: Arg, + items: c_int = 1, + sides: []const Side = &.{}, + limit: f32 = 0, + out_half: bool = false, + partial: u64 = 0, + parts: c_int = 1, +}; + +/// A kernel of the registry: its launch on this backend's kernels. +pub const Launch = *const fn (*const Kernels, Call) Error!void; +pub const Registry = registry.Registry(Launch); +pub const Entry = Registry.E; + +pub const bit_widths = [_]c_int{ 2, 3, 4, 5, 6, 8 }; +const row_counts = [_]u8{ 1, 2, 4, 8 }; +const piece_counts = [_]u8{ 1, 2, 4 }; + +pub const lane_rows = 8; // kLaneRows +pub const lane_group_max = 128; +const fast_n = 256; +const stream_cbs = [_]c_int{ 2, 4, 8 }; // columns a lane carries in the stream tile +const stream_rows = [_]u8{ 1, 2, 4 }; // its row counts: columns * rows <= 16 +const stream_waves = 4; // kStreamWaves +const streams_wanted = 3000; // kStreamWavesWanted +const stream_code_words = 32; // kStreamCodeWords + +/// The K-parallel tiles of a short prompt: cb columns a lane set, r rows a pass over up to rb row blocks. +pub const KpTile = struct { cb: c_int, r: c_int, waves: c_int, rb: c_int, loop: bool = true }; +pub const kp_tiles = [_]KpTile{ + .{ .cb = 8, .r = 1, .waves = 2, .rb = 2, .loop = false }, + .{ .cb = 4, .r = 4, .waves = 2, .rb = 4 }, + .{ .cb = 4, .r = 8, .waves = 2, .rb = 4, .loop = false }, + .{ .cb = 4, .r = 2, .waves = 2, .rb = 4 }, +}; + +/// The GEMM tiles of the m >= 64 products: `gemm` (the default) or the reference `block`. +pub const Tile = enum { gemm, block }; + +/// Which GEMM tile of the 128-row family a launch runs: the matrix cores, the dot2 tile, or the reference tile. +pub const BlockKind = enum { matrix, gemm, block }; + +pub const Kernels = struct { + /// Whether block shape `tier` can take `m` rows: a tile that does not loop over its rows holds rb * r of them. + pub fn tierTakes(tier: usize, m: c_int) bool { + return tier >= kp_tiles.len or kp_tiles[tier].loop or m <= kp_tiles[tier].rb * kp_tiles[tier].r; + } + + caps: Caps, + wmma: bool, + /// gfx11: the matrix-core GEMM tile runs (gfx12's WMMA has other layouts). + matrix: bool, + /// `off` runs products on dot2 tiles, `on` and `auto` on matrix cores where a tile exists. + mode: Matrix, + /// Which GEMM tile the products take; the policy's reference switch picks the reference one. + tile: Tile, + lanes: [bit_widths.len][row_counts.len][piece_counts.len]Function, + row: [bit_widths.len][piece_counts.len]Function, + /// The stream tile (tiles/stream.hpp) by width, rows and columns a lane; null where columns * rows > 16. + stream: [bit_widths.len][stream_rows.len][stream_cbs.len]?Function, + /// The same tile with the (gate | up) activation as its epilogue. + pairs: [bit_widths.len][stream_rows.len][stream_cbs.len]?Function, + /// Off keeps the decode tiles before the stream tile (the policy's reference switch). + stream_on: bool, + block: [bit_widths.len]Function, + gemm: [bit_widths.len]Function, + wmma_gemm: [bit_widths.len]Function, + kp: [bit_widths.len][kp_tiles.len]Function, + span: [2]Function, + fold: Function, + wide: Function, + tiled: Function, + reference: Function, + fill: Function, + reg: Registry, + + /// `tiles` holds dot2_tiles.hip's kernels, `dot2` dot2.hip's; bf16 on the WMMA build, fp16 on RDNA2. + pub fn load(tiles_obj: Module, dot2_obj: Module, caps: Caps, choices: Choices) Error!Kernels { + var k: Kernels = undefined; + const wmma = caps.act == .bf16; + k.caps = caps; + k.wmma = wmma; + k.matrix = wmma and caps.matrix == .wmma11; + k.mode = choices.matrix; + k.tile = if (choices.gemm) .gemm else .block; + k.stream_on = choices.stream; + k.reg = Registry.init(tableFor(caps), &mlx_entries.all); + k.reg.verify(k.env(), .mlx) catch return error.Invalid; + // the GEMM tile's rows of x a lane keeps (tiles/gemm.hpp GemmShape): 8 for BF16, 16 for FP16 + if (wmma) try k.resolve("7DotBF16", "Li8E", tiles_obj) else try k.resolve("6DotF16", "Li16E", tiles_obj); + const r = "_ZN2tf4rocm"; + k.span = .{ try dot2_obj.function(r ++ "16affine_dot2_spanILi1EEEvNS0_6AffineEPfi"), try dot2_obj.function(r ++ "16affine_dot2_spanILi8EEEvNS0_6AffineEPfi") }; + k.fold = try dot2_obj.function(r ++ "16affine_dot2_foldEPKfNS0_10GroupTableES3_Pfiii"); + k.wide = try dot2_obj.function(r ++ "16affine_dot2_wideENS0_6AffineE"); + k.tiled = try dot2_obj.function(r ++ "17affine_dot2_tiledENS0_6AffineE"); + k.reference = try dot2_obj.function(r ++ "18affine_dot2_kernelENS0_6AffineE"); + k.fill = try dot2_obj.function(r ++ "13fill_byte_lutEP6__half"); + return k; + } + + fn resolve(k: *Kernels, comptime dot: []const u8, comptime shape: []const u8, m: Module) Error!void { + @setEvalBranchQuota(200_000); + inline for (bit_widths, 0..) |bits, b| { + k.block[b] = try m.function(std.fmt.comptimePrint("_ZN2tf4rocm17affine_dot2_blockINS0_{s}ELi{d}EEEvNS0_6AffineE", .{ dot, bits })); + if (k.matrix) k.wmma_gemm[b] = try m.function(std.fmt.comptimePrint("_ZN2tf4rocm16affine_wmma_gemmILi{d}EEEvNS0_6AffineE", .{bits})); + k.gemm[b] = try m.function(std.fmt.comptimePrint("_ZN2tf4rocm17affine_gemm_blockINS0_{s}ELi{d}E{s}EEvNS0_6AffineE", .{ dot, bits, shape })); + inline for (kp_tiles, 0..) |t, i| { + k.kp[b][i] = try m.function(std.fmt.comptimePrint("_ZN2tf4rocm14affine_gemm_kpINS0_{s}ELi{d}ELi{d}ELi{d}ELi{d}ELi{d}ELb{d}EEEvNS0_6AffineE", .{ dot, bits, t.cb, t.r, t.waves, t.rb, @intFromBool(t.loop) })); + } + inline for (piece_counts, 0..) |pieces, p| { + k.row[b][p] = try m.function(std.fmt.comptimePrint("_ZN2tf4rocm15affine_dot2_rowINS0_{s}ELi{d}ELi{d}EEEvNS0_6AffineEi", .{ dot, bits, pieces })); + inline for (row_counts, 0..) |rows, r| { + k.lanes[b][r][p] = try m.function(std.fmt.comptimePrint("_ZN2tf4rocm17affine_dot2_lanesINS0_{s}ELi{d}ELi{d}ELi{d}EEEvNS0_6AffineE", .{ dot, bits, rows, pieces })); + } + } + inline for (stream_rows, 0..) |rows, r| { + inline for (stream_cbs, 0..) |cb, c| { + k.stream[b][r][c] = if (cb * rows <= 16) + try m.function(std.fmt.comptimePrint("_ZN2tf4rocm18affine_dot2_streamINS0_{s}ELi{d}ELi{d}ELi{d}ELb0EEEvNS0_6AffineENS0_11StreamSidesEii", .{ dot, bits, rows, cb })) + else + null; + k.pairs[b][r][c] = if (cb * rows <= 16) + try m.function(std.fmt.comptimePrint("_ZN2tf4rocm18affine_dot2_streamINS0_{s}ELi{d}ELi{d}ELi{d}ELb1EEEvNS0_6AffineENS0_11StreamSidesEii", .{ dot, bits, rows, cb })) + else + null; + } + } + } + } + + /// fp16(bf16(code)) for every byte into the module's constant table: the RDNA2 fp16 tiles read it. Once a device. + pub fn fillByteLut(k: *const Kernels, r: *const runtime.Runtime, dot2_obj: Module) Error!void { + if (k.wmma) return; + const lut = try dot2_obj.global("_ZN2tf4rocm8kByteF16E"); + var args: hl.Args = .{}; + try args.add(lut.address); + try hl.launch(k.fill, .{ .grid = .{ .x = 1 }, .block = .{ .x = 256 } }, .{ .r = r, .handle = null }, &args); + try runtime.check(r.api.hipStreamSynchronize(null)); + } + + /// Launches on `s`; the counting stream runs nothing. + fn go(r: *const runtime.Runtime, f: Function, grid: hl.Dim3, block: hl.Dim3, s: abi.Stream, args: *hl.Args) Error!void { + if (s == util.counting) return; + try hl.launch(f, .{ .grid = grid, .block = block }, .{ .r = r, .handle = s }, args); + } + + fn refuse(what: []const u8) Error { + std.log.err("affine: {s}", .{what}); + return error.Invalid; + } + + fn bitIndex(bits: c_int) ?usize { + return std.mem.indexOfScalar(c_int, &bit_widths, bits); + } + + fn pieceIndex(group: c_int) usize { + return switch (group) { + 32 => 0, + 64 => 1, + else => 2, + }; + } + + fn cdiv(n: c_int, by: c_int) c_uint { + return @intCast(@divTrunc(n + by - 1, by)); + } + + /// Groups a lane covers: the groups rounded up to a power of two, at most 32; none under four groups. + pub fn rowLanes(groups: c_int) c_int { + if (groups < 4) return 0; + var lpc: c_int = 4; + while (lpc < groups and lpc < 32) lpc <<= 1; + return lpc; + } + + /// The lanes a column takes in the K-parallel tile: one a group, 32 at most (kp_lanes). + fn kpLanes(groups: c_int) c_int { + return if (groups > 16) 32 else if (groups > 8) 16 else 8; + } + + /// The bytes the GEMM tile's piece loads need the words aligned to, by width. + pub fn gemmAlign(bits: c_int) u64 { + return switch (bits) { + 4, 8 => 16, + 2, 6 => 8, + else => 4, + }; + } + + // ---- what the choice sees of this build and of a call ---- + + /// The GPU and the run's switches as the registry reads them. + pub fn env(k: *const Kernels) registry.Env { + return .{ .bf16 = k.wmma, .matrix = k.matrix, .matrix_on = k.matrix and k.mode != .off, .stream_on = k.stream_on, .gemm_on = k.tile == .gemm }; + } + + /// The MLX entry that takes a product, or null. + pub fn choose(k: *const Kernels, op: registry.Op, path: registry.Path, shape: registry.Shape) ?*const Entry { + return k.reg.select(k.env(), .mlx, op, path, shape); + } + + /// The costs of the GPU's generation: RDNA2's, or the gfx11 ones (RDNA4 takes them for its dot2 tiles). + fn tableFor(caps: Caps) *const tuning.Table { + return switch (caps.generation) { + .rdna2 => &tuning.gfx1030, + .rdna3, .rdna3_5, .rdna4 => &tuning.gfx1100, + }; + } + + /// The product of `a` as a shape: `items` is a routed plan's item count. + pub fn shapeOf(a: Arg, items: c_int) registry.Shape { + const kind: quant.Tables = switch (a.scale.kind) { + 1 => .bf16, + 2 => .f16, + else => .f32, + }; + return .{ + .m = @intCast(@max(a.m, 0)), + .n = @intCast(@max(a.n, 0)), + .k = @intCast(@max(a.k, 0)), + .bits = std.math.cast(u8, a.bits) orelse 0, + .group = std.math.cast(u16, a.group) orelse 0, + .fp16 = a.fp16 != 0, + .tables = kind, + .tables_alike = a.scale.kind == a.bias.kind, + .x_aligned = a.x % 16 == 0, + .words_aligned = a.words % gemmAlign(a.bits) == 0, + .items = if (a.route.items != 0) @intCast(@max(items, 0)) else 0, + }; + } + + // ---- the tiles ---- + + /// The stream tile on `total_n` columns (a group's sum); `sides` counts them off block by block when it has any. + pub fn streamGo(k: *const Kernels, r: *const runtime.Runtime, a: Arg, sides_in: StreamSides, total_n: c_int, items: c_int, s: abi.Stream) Error!void { + const b = bitIndex(a.bits).?; + var sides = sides_in; + // a pair's lane carries half as many output columns: a gate column and its up column make one + const pair_div: c_int = if (sides.pair_cols > 0) 2 else 1; + var lpc_log2: u5 = 0; + while ((@as(c_int, 1) << lpc_log2) < (a.k >> 5) and lpc_log2 < 5) lpc_log2 += 1; + const ri: usize = if (a.m == 1) 0 else if (a.m == 2) 1 else 2; + // the widest column count that still fills the card with waves, within the registers the lane's code words take + var pick: usize = 0; + var c: usize = stream_cbs.len; + while (c > 0) { + c -= 1; + if (stream_cbs[c] * stream_rows[ri] > 16 or stream_cbs[c] * a.bits > stream_code_words) continue; + pick = c; + const per_block: c_int = stream_waves * (@as(c_int, 32) >> lpc_log2) * @divExact(stream_cbs[c], pair_div); + if (@as(u64, cdiv(total_n, per_block)) * stream_waves * @as(u64, @intCast(items)) * cdiv(a.m, stream_rows[ri]) >= streams_wanted) break; + } + const per_block: c_int = stream_waves * (@as(c_int, 32) >> lpc_log2) * @divExact(stream_cbs[pick], pair_div); + var blocks: c_uint = cdiv(total_n, per_block); + if (sides.count > 0) { + blocks = 0; + for (0..@intCast(sides.count)) |i| { + sides.first[i] = @intCast(blocks); + blocks += cdiv(sides.n[i], per_block); + } + sides.first[@intCast(sides.count)] = @intCast(blocks); + } + var args: hl.Args = .{}; + try args.add(a); + try args.add(sides); + try args.add(@as(c_int, lpc_log2)); + try args.add(@as(c_int, switch (a.group) { + 32 => 0, + 64 => 1, + else => 2, + })); + const f = (if (sides.pair_cols > 0) k.pairs[b][ri][pick] else k.stream[b][ri][pick]).?; + try go(r, f, .{ .x = blocks, .y = cdiv(a.m, stream_rows[ri]), .z = @intCast(items) }, .{ .x = 32 * stream_waves }, s, &args); + } + + /// One row on the row tile: a lane owns a group, a wave reads a column's row in one run. + pub fn rowGo(k: *const Kernels, r: *const runtime.Runtime, a: Arg, s: abi.Stream, items: c_int) Error!void { + const b = bitIndex(a.bits) orelse return refuse("bits"); + var args: hl.Args = .{}; + try args.add(a); + try args.add(rowLanes(@divExact(a.k, a.group))); + try go(r, k.row[b][pieceIndex(a.group)], .{ .x = cdiv(a.n, 128), .z = @intCast(items) }, .{ .x = 128 }, s, &args); + } + + /// Up to 8 rows on the column tile. + pub fn lanesGo(k: *const Kernels, r: *const runtime.Runtime, a: Arg, s: abi.Stream, items: c_int) Error!void { + const b = bitIndex(a.bits) orelse return refuse("bits"); + var args: hl.Args = .{}; + try args.add(a); + const ri: usize = if (a.m == 1) 0 else if (a.m == 2) 1 else if (a.m <= 4) 2 else 3; + try go(r, k.lanes[b][ri][pieceIndex(a.group)], .{ .x = cdiv(a.n, 32), .z = @intCast(items) }, .{ .x = 256 }, s, &args); + } + + /// The wide tile of the RDNA2 decode products of 9 rows and more. + pub fn wideGo(k: *const Kernels, r: *const runtime.Runtime, a: Arg, s: abi.Stream) Error!void { + var args: hl.Args = .{}; + try args.add(a); + try go(r, k.wide, .{ .x = cdiv(a.n, 32), .y = cdiv(a.m, 128) }, .{ .x = 512 }, s, &args); + } + + /// Any group width up to 128 that the others do not take, 16 columns by 16 rows a block. + pub fn tiledGo(k: *const Kernels, r: *const runtime.Runtime, a: Arg, s: abi.Stream) Error!void { + var args: hl.Args = .{}; + try args.add(a); + try go(r, k.tiled, .{ .x = cdiv(a.n, 16), .y = cdiv(a.m, 16) }, .{ .x = 256 }, s, &args); + } + + /// The one-thread tile every product has: the reference of the others. + pub fn referenceGo(k: *const Kernels, r: *const runtime.Runtime, a: Arg, s: abi.Stream) Error!void { + var args: hl.Args = .{}; + try args.add(a); + try go(r, k.reference, .{ .x = cdiv(a.n, 32), .y = @intCast(a.m) }, .{ .x = 32 }, s, &args); + } + + /// The decode tile over groups [z * per, (z + 1) * per) into `partial`, then the fold in group order. + pub fn splitGo(k: *const Kernels, r: *const runtime.Runtime, a: Arg, partial: u64, parts: c_int, s: abi.Stream) Error!void { + const groups = @divTrunc(a.k, a.group); + var args: hl.Args = .{}; + try args.add(a); + try args.add(partial); + try args.add(@divExact(groups, parts)); + try go(r, k.span[if (a.m == 1) 0 else 1], .{ .x = cdiv(a.n, fast_n), .y = cdiv(a.m, 8), .z = @intCast(parts) }, .{ .x = fast_n }, s, &args); + var fold: hl.Args = .{}; + try fold.add(partial); + try fold.add(a.scale); + try fold.add(a.bias); + try fold.add(a.out); + try fold.add(a.m); + try fold.add(a.n); + try fold.add(groups); + try go(r, k.fold, .{ .x = cdiv(a.n, fast_n), .y = @intCast(a.m) }, .{ .x = fast_n }, s, &fold); + } + + /// The 128 x 128 tile of a kind over every item of a plan (or the plain product). + pub fn blockGo(k: *const Kernels, r: *const runtime.Runtime, a: Arg, s: abi.Stream, items: c_int, kind: BlockKind) Error!void { + const b = bitIndex(a.bits) orelse return refuse("bits"); + var args: hl.Args = .{}; + try args.add(a); + const f = switch (kind) { + .matrix => k.wmma_gemm[b], + .gemm => k.gemm[b], + .block => k.block[b], + }; + try go(r, f, .{ .x = cdiv(a.n, 128), .y = cdiv(a.m, 128), .z = @intCast(items) }, .{ .x = 256 }, s, &args); + } + + /// K-parallel tile `tier` (an index of kp_tiles) of a short prompt. + pub fn kpGo(k: *const Kernels, r: *const runtime.Runtime, a: Arg, s: abi.Stream, items: c_int, tier: usize) Error!void { + const b = bitIndex(a.bits) orelse return refuse("bits"); + var args: hl.Args = .{}; + try args.add(a); + const t = kp_tiles[tier]; + const sets = @divExact(32, kpLanes(@divExact(a.k, a.group))); + const blocks = @min(cdiv(a.m, t.r), @as(c_uint, @intCast(t.rb))); + try go(r, k.kp[b][tier], .{ .x = cdiv(a.n, t.waves * t.cb * sets) * blocks, .z = @intCast(items) }, .{ .x = @intCast(32 * t.waves) }, s, &args); + } + + // ---- the entry points ---- + + /// Prefill's tile, same bits however a prompt is cut: matrix on gfx11 unless off, else dot2 GEMM; few rows K-split. + pub fn prefillLaunch(k: *const Kernels, r: *const runtime.Runtime, a: Arg, s: abi.Stream, items: c_int) Error!void { + const op: registry.Op = if (a.route.items != 0) .routed else .project; + const e = k.choose(op, .prefill, shapeOf(a, items)) orelse return refuse("prefill shape"); + try e.launch(k, .{ .r = r, .s = s, .arg = a, .items = items }); + } + + /// launch_affine on the auto schedule: `schedule` 3 is prefill's, 4 a lane round's; `partial`, `parts` the tests'. + pub fn run(k: *const Kernels, r: *const runtime.Runtime, arg: Arg, schedule: c_int, s: abi.Stream, partial: u64, parts: c_int, out_half: bool) Error!void { + var a = arg; + if (schedule == 1) { + if (a.fp16 == 0 or k.wmma) return refuse("the reference schedule takes fp16 on RDNA2"); + return k.referenceGo(r, a, s); + } + if (schedule == 2 or schedule > 4) return refuse("no such schedule"); + var shape = shapeOf(a, 1); + shape.round = schedule == 4; + shape.parts = if (partial != 0 and parts > 1) @intCast(parts) else 1; + const e = k.choose(.project, if (schedule == 3) .prefill else .decode, shape) orelse return refuse("no tile takes this product"); + if (out_half) { + // the activation type's output is the decode tile's: fp16 on RDNA2, and either type from the stream tile + if (schedule == 3 or parts > 1 or !e.roundsAct(shape)) return refuse("fp16 output is the decode tile"); + a.out16 = a.out; + a.out = 0; + } + try e.launch(k, .{ .r = r, .s = s, .arg = a, .partial = partial, .parts = parts, .out_half = out_half }); + } + + /// affine_routed_launch: every item of a plan in one launch; `arg.m` is the most rows an item holds. + pub fn routed(k: *const Kernels, r: *const runtime.Runtime, arg: Arg, items: c_int, s: abi.Stream) Error!void { + return k.routedWith(r, arg, items, s, k.tile); + } + + pub fn routedWith(k: *const Kernels, r: *const runtime.Runtime, arg: Arg, items: c_int, s: abi.Stream, tile: Tile) Error!void { + // the family's own activation type: bf16 on the WMMA build, fp16 on RDNA2 + if ((arg.fp16 != 0) == k.wmma or arg.route.items == 0 or arg.route.members == 0 or items < 1 or arg.route.x_div < 1) return refuse("routed plan"); + var environment = k.env(); + environment.gemm_on = tile == .gemm; + const e = k.reg.select(environment, .mlx, .routed, .decode, shapeOf(arg, items)) orelse return refuse("no tile takes this plan"); + try e.launch(k, .{ .r = r, .s = s, .arg = arg, .items = items }); + } + + /// The stacked (gate | up) product as silu(gate) * up into `out16`, clamped by `limit` above 0; false if not taken. + pub fn pairRun(k: *const Kernels, r: *const runtime.Runtime, arg: Arg, limit: f32, items: c_int, s: abi.Stream) Error!bool { + var shape = shapeOf(arg, items); + shape.pairs = arg.out16 != 0; + const e = k.choose(.routed_act, .decode, shape) orelse return false; + try e.launch(k, .{ .r = r, .s = s, .arg = arg, .items = items, .limit = limit }); + return true; + } + + /// Up to four products of `m` rows over one x in one launch; outputs (m, n) fp32, or activation type if `out_half`. + pub fn groupRun(k: *const Kernels, r: *const runtime.Runtime, arg: Arg, group: []const Side, out_half: bool, s: abi.Stream) Error!void { + if (group.len == 0 or group.len > 4) return refuse("group shape"); + var a = arg; + a.n = 0; + for (group) |side| a.n = @max(a.n, side.n); + var shape = shapeOf(a, 1); + shape.round = true; + const e = k.choose(.group, .decode, shape) orelse return refuse("group shape"); + try e.launch(k, .{ .r = r, .s = s, .arg = a, .sides = group, .out_half = out_half }); + } + + /// The stream tile over a group: the sides' addresses and widths in one launch. + pub fn groupGo(k: *const Kernels, r: *const runtime.Runtime, arg: Arg, group: []const Side, out_half: bool, s: abi.Stream) Error!void { + var a = arg; + var sides: StreamSides = .{ .count = @intCast(group.len), .out_half = @intFromBool(out_half) }; + var total: c_int = 0; + a.n = 0; + for (group, 0..) |side, i| { + sides.words[i] = side.words; + sides.scale[i] = side.scale; + sides.bias[i] = side.bias; + sides.out[i] = side.out; + sides.n[i] = side.n; + total += side.n; + a.n = @max(a.n, side.n); + } + a.words = group[0].words; + a.scale.p = group[0].scale; + a.bias.p = group[0].bias; + try k.streamGo(r, a, sides, total, 1, s); + } + + /// The split count of a decode launch: 1 unless `mode` is 2 (the tests' forced comparison) and the groups divide. + pub fn splitCount(m: c_int, n: c_int, k: c_int, group: c_int, mode: c_int) c_int { + if (mode != 2 or m < 1 or n < 512) return 1; + if (!(group == 32 or group == 64 or group == 128) or k < group or @rem(k, group) != 0) return 1; + const groups = @divTrunc(k, group); + if (groups < 2) return 1; + // A full row tile or a wide column grid already fills the card. + const blocks = @divTrunc(n + fast_n - 1, fast_n) * @divTrunc(m + 8 - 1, 8); + if (blocks < 1) return 1; + var want = @divTrunc(256, blocks); + if (want < 2) want = 2; + if (want > groups) want = groups; + var count = want; + while (count >= 2) : (count -= 1) { + if (@rem(groups, count) == 0) return count; + } + return 1; + } +}; + +test "the split count follows the C rule" { + try std.testing.expectEqual(@as(c_int, 1), Kernels.splitCount(1, 4096, 4096, 64, 0)); + try std.testing.expectEqual(@as(c_int, 1), Kernels.splitCount(1, 256, 4096, 64, 2)); + try std.testing.expectEqual(@as(c_int, 8), Kernels.splitCount(1, 4096, 512, 64, 2)); +} + +test "the lane groups of a row tile" { + try std.testing.expectEqual(@as(c_int, 0), Kernels.rowLanes(3)); + try std.testing.expectEqual(@as(c_int, 4), Kernels.rowLanes(4)); + try std.testing.expectEqual(@as(c_int, 32), Kernels.rowLanes(64)); +} + +test { + _ = mlx_entries; +} diff --git a/zig/src/hip/launches/attention.zig b/zig/src/hip/launches/attention.zig new file mode 100644 index 00000000000..ea31be1c9f4 --- /dev/null +++ b/zig/src/hip/launches/attention.zig @@ -0,0 +1,162 @@ +//! Attention launches: causal prefill and decode, the gate and the cache write. + +const Launcher = @import("../launches.zig").Launcher; +const util = @import("util.zig"); +const S = util.S; +const P = util.P; +const C = util.C; +const F = util.F; +const CF = util.CF; +const CI = util.CI; +const Args = util.Args; +const Error = util.Error; +const ad = util.ad; +const dim = util.dim; +const cdiv = util.cdiv; +const invalid = util.invalid; + +pub fn tf_causal(l: *const Launcher, q: CF, k: C, v: C, out: F, batch: c_int, qlen: c_int, span: c_int, heads: c_int, kv_heads: c_int, d: c_int, scale: f32, q_pos0: c_int, k_sb: c_longlong, k_sh: c_longlong, k_ss: c_longlong, v_sb: c_longlong, v_sh: c_longlong, v_ss: c_longlong, cache_kind: c_int, scores: F, stats: F, partials: F, s: S, pos: CI) Error!void { + if (d < 1 or d > 256 or heads < 1 or kv_heads < 1 or @rem(heads, kv_heads) != 0 or batch < 1 or qlen < 1 or span < 1 or q_pos0 < 0) { + return invalid("causal attention"); + } + if (cache_kind < 0 or cache_kind > 2) return invalid("causal attention cache kind"); + const kind: usize = @intCast(cache_kind); + const visible: c_int = @min(q_pos0 + 1, span); + if (scores != null) { + if (qlen != 1 or stats == null or partials == null) return invalid("the decode walk"); + // With a device position the keys in use are read on the device and the grid covers the whole cache. + const tiles: c_int = @intCast(if (pos != null) cdiv(span, 128) else cdiv(visible, 128)); + const head_grid = dim(heads, batch, 1); + var a: Args = .{}; + try a.add(ad(q)); + try a.add(ad(k)); + try a.add(ad(scores)); + try a.add(span); + try a.add(heads); + try a.add(kv_heads); + try a.add(d); + try a.add(scale); + try a.add(visible); + try a.add(k_sb); + try a.add(k_sh); + try a.add(k_ss); + try a.add(ad(pos)); + // a warp scores a key: four warps a block + try l.go(l.score_keys[kind], dim(cdiv(span, 4), heads, batch), dim(128, 1, 1), 0, s, &a); + var b: Args = .{}; + try b.add(ad(scores)); + try b.add(ad(stats)); + try b.add(span); + try b.add(visible); + try b.add(ad(pos)); + try l.go(l.softmax_stats, head_grid, dim(256, 1, 1), 0, s, &b); + var c: Args = .{}; + try c.add(ad(scores)); + try c.add(ad(stats)); + try c.add(ad(v)); + try c.add(ad(partials)); + try c.add(span); + try c.add(heads); + try c.add(kv_heads); + try c.add(d); + try c.add(visible); + try c.add(v_sb); + try c.add(v_sh); + try c.add(v_ss); + try c.add(ad(pos)); + try l.go(l.apply_values[kind], dim(tiles, heads, batch), dim(256, 1, 1), 0, s, &c); + var e: Args = .{}; + try e.add(ad(partials)); + try e.add(ad(out)); + try e.add(tiles); + try e.add(d); + try l.go(l.sum_partials, head_grid, dim(256, 1, 1), 0, s, &e); + return; + } + var a: Args = .{}; + try a.add(ad(q)); + try a.add(ad(k)); + try a.add(ad(v)); + try a.add(ad(out)); + try a.add(qlen); + try a.add(span); + try a.add(heads); + try a.add(kv_heads); + try a.add(d); + try a.add(scale); + try a.add(q_pos0); + try a.add(k_sb); + try a.add(k_sh); + try a.add(k_ss); + try a.add(v_sb); + try a.add(v_sh); + try a.add(v_ss); + // a 16-bit cache of whole 64-wide heads takes the 64-row tile (attention=f32: 16-row); odd heads a wave a query + if (kind < 2 and @rem(d, 64) == 0 and d <= 256 and @rem(k_ss, 8) == 0 and @rem(v_ss, 8) == 0 and l.wide) { + try l.go(l.fa_wide[kind], dim(cdiv(qlen, 64), heads, batch), dim(256, 1, 1), 0, s, &a); + } else if (d >= 2 and @rem(d, 2) == 0) { + try l.go(l.fa_prefill[kind], dim(cdiv(qlen, 16), heads, batch), dim(256, 1, 1), 0, s, &a); + } else { + try l.go(l.causal[kind], dim(qlen, heads, batch), dim(32, 1, 1), 0, s, &a); + } +} + +/// The 64-row prefill tile over a stream's pages: q (heads, qlen, d) fp32 against `span` positions, 16-bit cache. +pub fn pagedCausal(l: *const Launcher, q: u64, k: u64, v: u64, table: u64, out: u64, qlen: usize, span: usize, heads: usize, kv_heads: usize, d: usize, scale: f32, q_pos0: usize, count: usize, cache_kind: c_int, s: S) Error!void { + if (d % 64 != 0 or d > 256 or heads % kv_heads != 0 or cache_kind < 0 or cache_kind > 1) return invalid("paged attention"); + var a: Args = .{}; + try a.add(q); + try a.add(k); + try a.add(v); + try a.add(out); + try a.add(@as(c_int, @intCast(qlen))); + try a.add(@as(c_int, @intCast(span))); + try a.add(@as(c_int, @intCast(heads))); + try a.add(@as(c_int, @intCast(kv_heads))); + try a.add(@as(c_int, @intCast(d))); + try a.add(scale); + try a.add(@as(c_int, @intCast(q_pos0))); + try a.add(table); + try a.add(@as(c_int, @intCast(count))); + try l.go(l.fa_paged[@intCast(cache_kind)], dim(cdiv(qlen, 64), heads, 1), dim(256, 1, 1), 0, s, &a); +} + +pub fn tf_attn_gate(l: *const Launcher, att: CF, qg: C, out: P, kind: c_int, len: c_int, heads: c_int, d: c_int, rows_major: c_int, s: S) Error!void { + var a: Args = .{}; + try a.add(ad(att)); + try a.add(ad(qg)); + try a.add(ad(out)); + try a.add(kind); + try a.add(len); + try a.add(heads); + try a.add(d); + try a.add(rows_major); + try l.flat(l.op.attn_gate, @as(i64, len) * heads * d, s, &a); +} + +pub fn tf_kv_write(l: *const Launcher, src: C, cache: P, kind: c_int, len: c_int, kv_heads: c_int, d: c_int, total: c_int, pos0: c_int, s: S) Error!void { + var a: Args = .{}; + try a.add(ad(src)); + try a.add(ad(cache)); + try a.add(kind); + try a.add(len); + try a.add(kv_heads); + try a.add(d); + try a.add(total); + try a.add(pos0); + try l.flat(l.op.kv_write, @as(i64, len) * kv_heads * d, s, &a); +} + +/// kv_write with the first slot read from the device (`pos`, one i32), so a captured graph replays at any position. +pub fn tf_kv_write_at(l: *const Launcher, src: C, cache: P, kind: c_int, len: c_int, kv_heads: c_int, d: c_int, total: c_int, pos: CI, s: S) Error!void { + var a: Args = .{}; + try a.add(ad(src)); + try a.add(ad(cache)); + try a.add(kind); + try a.add(len); + try a.add(kv_heads); + try a.add(d); + try a.add(total); + try a.add(ad(pos)); + try l.flat(l.op.kv_write_at, @as(i64, len) * kv_heads * d, s, &a); +} diff --git a/zig/src/hip/launches/conv.zig b/zig/src/hip/launches/conv.zig new file mode 100644 index 00000000000..59f2cb0af49 --- /dev/null +++ b/zig/src/hip/launches/conv.zig @@ -0,0 +1,97 @@ +//! Causal conv launches: decode, window rows, prefill and the split with its norms and gates. + +const Launcher = @import("../launches.zig").Launcher; +const util = @import("util.zig"); +const S = util.S; +const C = util.C; +const F = util.F; +const CF = util.CF; +const Args = util.Args; +const Error = util.Error; +const ad = util.ad; +const dim = util.dim; +const cdiv = util.cdiv; +const invalid = util.invalid; +const PlanArgs = @import("plan.zig").PlanArgs; + +/// decode.hip's ConvArgs: the linear attention's conv launch. +pub const ConvArgs = extern struct { + x: u64, + kind: c_int, + weight: u64, + state: u64, + states: u64 = 0, + qn: u64, + kn: u64, + v: u64, + channels: c_int, + kernel: c_int, + rows: c_int, + kw: c_int, + vw: c_int, + qw: u64 = 0, + kw_w: u64 = 0, + eps: f32 = 0, + norm: c_int = 0, + ga: u64 = 0, + gb: u64 = 0, + a_log: u64 = 0, + dt_bias: u64 = 0, + gate: u64 = 0, + beta: u64 = 0, + gcount: c_int = 0, + heads: c_int = 0, + /// A round's plan: a grid row a slot, its rows and state from the plan (no plan: this launch's own). + plan: PlanArgs = .{}, + layer: c_int = 0, + slots: c_int = 1, +}; + +pub fn tf_conv_decode(l: *const Launcher, x: CF, weight: CF, state: F, y: F, batch: c_int, channels: c_int, kernel: c_int, s: S) Error!void { + var a: Args = .{}; + try a.add(ad(x)); + try a.add(ad(weight)); + try a.add(ad(state)); + try a.add(ad(y)); + try a.add(channels); + try a.add(kernel); + try l.go(l.conv_decode, dim(cdiv(channels, 128), batch, 1), dim(128, 1, 1), 0, s, &a); +} + +pub fn tf_conv_rows(l: *const Launcher, x: CF, weight: CF, state: F, y: F, states: F, rows: c_int, channels: c_int, kernel: c_int, s: S) Error!void { + var a: Args = .{}; + try a.add(ad(x)); + try a.add(ad(weight)); + try a.add(ad(state)); + try a.add(ad(y)); + try a.add(ad(states)); + try a.add(channels); + try a.add(kernel); + try a.add(rows); + try l.go(l.conv_rows, dim(cdiv(channels, 128), 1, 1), dim(128, 1, 1), 0, s, &a); +} + +/// A window's rows through the linear attention's conv, split into q, k and v, normed and gated when `c` asks. +pub fn tf_conv_split(l: *const Launcher, c: ConvArgs, s: S) Error!void { + if (c.kernel < 1 or c.kernel > 8 or (c.norm != 0 and (c.norm != 128 or @rem(c.kw, 128) != 0))) return invalid("conv split"); + var a: Args = .{}; + try a.add(c); + const gate_blocks = if (c.ga != 0) cdiv(c.gcount, 128) else 0; + try l.go(l.dec.conv_split, dim(cdiv(c.channels, 128) + gate_blocks, c.slots, 1), dim(128, 1, 1), 0, s, &a); +} + +pub fn tf_conv_prefill(l: *const Launcher, x: C, kind: c_int, weight: CF, state: CF, out: F, new_state: F, len: c_int, channels: c_int, kernel: c_int, s: S) Error!void { + var a: Args = .{}; + try a.add(ad(x)); + try a.add(kind); + try a.add(ad(weight)); + try a.add(ad(state)); + try a.add(ad(out)); + try a.add(ad(new_state)); + try a.add(len); + try a.add(channels); + try a.add(kernel); + // a thread a channel over 16 rows (conv_prefill_kernel's kConvRows), at most 8 taps + if (kernel > 8) return invalid("conv_prefill"); + try l.go(l.op.conv_prefill, dim(cdiv(channels, 256), @max(1, cdiv(len, 16)), 1), dim(256, 1, 1), 0, s, &a); +} diff --git a/zig/src/hip/launches/draw.zig b/zig/src/hip/launches/draw.zig new file mode 100644 index 00000000000..deba1ab5fe3 --- /dev/null +++ b/zig/src/hip/launches/draw.zig @@ -0,0 +1,37 @@ +//! Argmax and top-k of logits rows: one 1024-thread block a row. + +const Launcher = @import("../launches.zig").Launcher; +const util = @import("util.zig"); +const S = util.S; +const C = util.C; +const P = util.P; +const I = util.I; +const CI = util.CI; +const Args = util.Args; +const Error = util.Error; +const ad = util.ad; +const dim = util.dim; + +/// out[r] = torch.argmax of row r of (rows, n) logits of `kind` (1 fp16, 2 bf16). +pub fn tf_argmax_rows(l: *const Launcher, logits: C, kind: c_int, rows: c_int, n: c_int, out: I, s: S) Error!void { + if (rows == 0) return; + var a: Args = .{}; + try a.add(ad(logits)); + try a.add(kind); + try a.add(n); + try a.add(ad(out)); + try l.go(l.op.argmax, dim(rows, 1, 1), dim(1024, 1, 1), 0, s, &a); +} + +/// Row r's ks[r] largest by (value desc, id asc) into ids and 16-bit values, `stride` apart; ks[r] = 0 skips the row. +pub fn tf_topk_rows(l: *const Launcher, logits: C, rows: c_int, n: c_int, ks: CI, stride: c_int, ids: I, values: P, s: S) Error!void { + if (rows == 0) return; + var a: Args = .{}; + try a.add(ad(logits)); + try a.add(n); + try a.add(ad(ks)); + try a.add(stride); + try a.add(ad(ids)); + try a.add(ad(values)); + try l.go(l.op.topk, dim(rows, 1, 1), dim(1024, 1, 1), 0, s, &a); +} diff --git a/zig/src/hip/launches/elementwise.zig b/zig/src/hip/launches/elementwise.zig new file mode 100644 index 00000000000..4f767f37fdb --- /dev/null +++ b/zig/src/hip/launches/elementwise.zig @@ -0,0 +1,94 @@ +//! Element-wise launches: embedding rows, casts, sums, column copies and the draft projection. + +const Launcher = @import("../launches.zig").Launcher; +const util = @import("util.zig"); +const S = util.S; +const P = util.P; +const C = util.C; +const CF = util.CF; +const CI = util.CI; +const Args = util.Args; +const Error = util.Error; +const ad = util.ad; +const dim = util.dim; + +pub fn tf_embed_rows(l: *const Launcher, words: C, scale: C, bias: C, scale_kind: c_int, ids: CI, n: c_int, bits: c_int, group: c_int, k: c_int, out: P, out_kind: c_int, s: S) Error!void { + var a: Args = .{}; + try a.add(ad(words)); + try a.add(ad(scale)); + try a.add(ad(bias)); + try a.add(scale_kind); + try a.add(ad(ids)); + try a.add(n); + try a.add(bits); + try a.add(group); + try a.add(k); + try a.add(ad(out)); + try a.add(out_kind); + try l.flat(l.op.embed_rows, @as(i64, n) * k, s, &a); +} + +pub fn tf_embed_dense(l: *const Launcher, table: CF, ids: CI, n: c_int, k: c_int, out: P, out_kind: c_int, s: S) Error!void { + var a: Args = .{}; + try a.add(ad(table)); + try a.add(ad(ids)); + try a.add(n); + try a.add(k); + try a.add(ad(out)); + try a.add(out_kind); + try l.flat(l.op.embed_dense, @as(i64, n) * k, s, &a); +} + +pub fn tf_cast(l: *const Launcher, src: C, skind: c_int, dst: P, dkind: c_int, n: c_longlong, s: S) Error!void { + var a: Args = .{}; + try a.add(ad(src)); + try a.add(skind); + try a.add(ad(dst)); + try a.add(dkind); + try a.add(n); + try l.flat(l.op.cast, n, s, &a); +} + +pub fn tf_silu_mul(l: *const Launcher, gate: C, up: C, out: P, kind: c_int, n: c_longlong, s: S) Error!void { + var a: Args = .{}; + try a.add(ad(gate)); + try a.add(ad(up)); + try a.add(ad(out)); + try a.add(kind); + try a.add(n); + try l.flat(l.op.silu_mul, n, s, &a); +} + +pub fn tf_add(l: *const Launcher, x: C, y: C, out: P, kind: c_int, n: c_longlong, s: S) Error!void { + var a: Args = .{}; + try a.add(ad(x)); + try a.add(ad(y)); + try a.add(ad(out)); + try a.add(kind); + try a.add(n); + try l.flat(l.op.add, n, s, &a); +} + +pub fn tf_copy_cols(l: *const Launcher, src: C, stride: c_longlong, offset: c_int, dst: P, kind: c_int, rows: c_int, cols: c_int, s: S) Error!void { + var a: Args = .{}; + try a.add(ad(src)); + try a.add(stride); + try a.add(offset); + try a.add(ad(dst)); + try a.add(kind); + try a.add(rows); + try a.add(cols); + try l.flat(l.op.copy_cols, @as(i64, rows) * cols, s, &a); +} + +pub fn tf_dense_rows(l: *const Launcher, x: C, kind: c_int, w: CF, out: P, rows: c_int, n: c_int, k: c_int, s: S) Error!void { + var a: Args = .{}; + try a.add(ad(x)); + try a.add(kind); + try a.add(ad(w)); + try a.add(ad(out)); + try a.add(rows); + try a.add(n); + try a.add(k); + try l.go(l.op.dense_rows, dim(n, rows, 1), dim(32, 1, 1), 0, s, &a); +} diff --git a/zig/src/hip/launches/mlx_entries.zig b/zig/src/hip/launches/mlx_entries.zig new file mode 100644 index 00000000000..b9c8fe26c88 --- /dev/null +++ b/zig/src/hip/launches/mlx_entries.zig @@ -0,0 +1,408 @@ +//! The registry's MLX affine entries: each tile with its needs, the shapes it has code for and its launch. + +const std = @import("std"); +const registry = @import("core").registry; +const tuning = @import("../tuning/tuning.zig"); +const affine = @import("affine.zig"); + +const Entry = affine.Entry; +const Shape = registry.Shape; +const Env = registry.Env; +const Call = affine.Call; +const Op = registry.Op; +const Kernels = affine.Kernels; +const Error = @import("../runtime.zig").Error; +const Launch = affine.Launch; + +// ---- what the GPU has and the run switched on + +fn always(_: Env) bool { + return true; +} + +fn rdna2(e: Env) bool { + return !e.bf16; +} + +fn matrixCores(e: Env) bool { + return e.matrix; +} + +fn streamOn(e: Env) bool { + return e.stream_on; +} + +fn gemmOn(e: Env) bool { + return e.gemm_on; +} + +fn matrixOn(e: Env) bool { + return e.matrix and e.matrix_on and e.gemm_on; +} + +// ---- the shapes the tiles have code for + +fn groupOk(s: Shape) bool { + return s.group == 32 or s.group == 64 or s.group == 128; +} + +fn widthOk(s: Shape) bool { + return switch (s.bits) { + 2, 3, 4, 5, 6, 8 => true, + else => false, + }; +} + +/// The words the GEMM tiles load wide, and tables of one kind. +fn gemmFits(s: Shape) bool { + return s.words_aligned and s.tables_alike; +} + +/// The stream tile: whole groups of a multiple of 32, x on 16 bytes, 16-bit tables of one kind. +fn streamShape(s: Shape) bool { + return s.n >= 1 and s.group != 0 and s.group % 32 == 0 and s.group <= affine.lane_group_max and s.k % s.group == 0 and + s.x_aligned and s.tables != .f32 and s.tables_alike and widthOk(s); +} + +fn lanesOk(s: Shape) bool { + return s.m >= 1 and s.m <= affine.lane_rows and s.n >= 1 and s.group != 0 and s.group % 32 == 0 and + s.group <= affine.lane_group_max and s.k % s.group == 0; +} + +fn rowOk(s: Shape) bool { + return s.m == 1 and lanesOk(s) and Kernels.rowLanes(@intCast(s.k / s.group)) != 0; +} + +fn blockOk(s: Shape) bool { + return s.m >= 1 and s.n >= 1 and s.group != 0 and s.group % 32 == 0 and s.k % s.group == 0 and s.k % 16 == 0; +} + +fn prefillOk(s: Shape) bool { + return s.m >= 1 and s.n >= 1 and groupOk(s) and s.k % s.group == 0 and s.k % 16 == 0; +} + +/// What the activation type's dot2 kernels take of a product: any group of an even width. +fn dot2Shape(s: Shape) bool { + return s.m >= 1 and s.n >= 1 and s.k >= 1 and s.group != 0 and s.group % 2 == 0 and s.k % s.group == 0; +} + +/// What a decode launch takes of a product on this build: the checks every tile of it shares. +fn valid(s: Shape) bool { + if (s.fp16) return dot2Shape(s); + return s.m >= 1 and s.n >= 1 and groupOk(s) and s.k % s.group == 0 and s.k % 16 == 0; +} + +fn routedOk(s: Shape) bool { + return groupOk(s) and s.items >= 1; +} + +// ---- the decode tiles of a plain product + +fn fitsSplit(s: Shape) bool { + return s.parts > 1 and s.fp16 and valid(s) and groupOk(s) and (s.k / s.group) % s.parts == 0; +} + +fn fitsStream(s: Shape) bool { + return streamShape(s) and (s.round or valid(s)); +} + +fn fitsRow(s: Shape) bool { + return valid(s) and groupOk(s) and rowOk(s); +} + +fn fitsLanes(s: Shape) bool { + return valid(s) and groupOk(s) and lanesOk(s); +} + +fn fitsWide(s: Shape) bool { + return valid(s) and groupOk(s) and s.m > 8 and (s.m < 64 or s.k % 16 != 0); +} + +fn fitsMatrix(s: Shape) bool { + return valid(s) and blockOk(s) and !s.fp16 and gemmFits(s); +} + +fn fitsGemm(s: Shape) bool { + return valid(s) and groupOk(s) and blockOk(s) and gemmFits(s); +} + +fn fitsBlock(s: Shape) bool { + return valid(s) and groupOk(s) and blockOk(s); +} + +fn fitsTiled(s: Shape) bool { + return dot2Shape(s) and !groupOk(s) and s.m > 1 and s.group <= 128; +} + +fn fitsReference(s: Shape) bool { + return dot2Shape(s); +} + +// ---- the decode tiles of a plan over stacked experts, a group of products and a plan's gate and up + +fn fitsRoutedStream(s: Shape) bool { + return routedOk(s) and streamShape(s); +} + +fn fitsRoutedRow(s: Shape) bool { + return routedOk(s) and rowOk(s); +} + +fn fitsRoutedLanes(s: Shape) bool { + return routedOk(s) and lanesOk(s); +} + +fn fitsRoutedMatrix(s: Shape) bool { + return routedOk(s) and blockOk(s) and !s.fp16 and gemmFits(s); +} + +fn fitsRoutedGemm(s: Shape) bool { + return routedOk(s) and blockOk(s) and gemmFits(s); +} + +fn fitsRoutedBlock(s: Shape) bool { + return routedOk(s) and blockOk(s); +} + +fn fitsGroup(s: Shape) bool { + return streamShape(s); +} + +fn fitsPair(s: Shape) bool { + return s.pairs and s.n >= 2 and s.n % 2 == 0 and streamShape(s); +} + +// ---- the prefill tiles + +fn kpFits(comptime tier: usize) *const fn (Shape) bool { + return struct { + fn f(s: Shape) bool { + return prefillOk(s) and gemmFits(s) and Kernels.tierTakes(tier, @intCast(s.m)); + } + }.f; +} + +fn fitsPrefillMatrix(s: Shape) bool { + return prefillOk(s) and !s.fp16 and gemmFits(s); +} + +fn fitsPrefillGemm(s: Shape) bool { + return prefillOk(s) and gemmFits(s); +} + +fn fitsPrefillBlock(s: Shape) bool { + return prefillOk(s); +} + +// ---- the launches + +fn launchStream(k: *const Kernels, c: Call) Error!void { + try k.streamGo(c.r, c.arg, .{}, c.arg.n, c.items, c.s); +} + +fn launchPair(k: *const Kernels, c: Call) Error!void { + try k.streamGo(c.r, c.arg, .{ .pair_cols = @divExact(c.arg.n, 2), .limit = c.limit }, @divExact(c.arg.n, 2), c.items, c.s); +} + +fn launchGroup(k: *const Kernels, c: Call) Error!void { + try k.groupGo(c.r, c.arg, c.sides, c.out_half, c.s); +} + +fn launchRow(k: *const Kernels, c: Call) Error!void { + try k.rowGo(c.r, c.arg, c.s, c.items); +} + +fn launchLanes(k: *const Kernels, c: Call) Error!void { + try k.lanesGo(c.r, c.arg, c.s, c.items); +} + +fn launchWide(k: *const Kernels, c: Call) Error!void { + try k.wideGo(c.r, c.arg, c.s); +} + +fn launchTiled(k: *const Kernels, c: Call) Error!void { + try k.tiledGo(c.r, c.arg, c.s); +} + +fn launchReference(k: *const Kernels, c: Call) Error!void { + try k.referenceGo(c.r, c.arg, c.s); +} + +fn launchSplit(k: *const Kernels, c: Call) Error!void { + try k.splitGo(c.r, c.arg, c.partial, c.parts, c.s); +} + +fn launchBlock(comptime kind: affine.BlockKind) Launch { + return struct { + fn f(k: *const Kernels, c: Call) Error!void { + try k.blockGo(c.r, c.arg, c.s, c.items, kind); + } + }.f; +} + +fn launchKp(comptime tier: usize) Launch { + return struct { + fn f(k: *const Kernels, c: Call) Error!void { + try k.kpGo(c.r, c.arg, c.s, c.items, tier); + } + }.f; +} + +// ---- the entries + +/// What an entry is besides its op, path and name. +const Spec = struct { + family: registry.Family, + fits: *const fn (Shape) bool, + launch: Launch, + caps: *const fn (Env) bool = &always, + policy: *const fn (Env) bool = &always, + rounds: registry.Rounds = .never, + round_any: bool = false, +}; + +fn entry(comptime op: Op, comptime path: registry.Path, comptime name: []const u8, comptime spec: Spec) Entry { + return .{ + .id = "mlx." ++ @tagName(op) ++ "." ++ @tagName(path) ++ "." ++ name, + .format = .mlx, + .op = op, + .path = path, + .family = spec.family, + .caps = spec.caps, + .policy = spec.policy, + .fits = spec.fits, + .rounds = spec.rounds, + .round_any = spec.round_any, + .launch = spec.launch, + }; +} + +const project_decode = [_]Entry{ + entry(.project, .decode, "split", .{ .family = .split, .fits = &fitsSplit, .launch = &launchSplit, .caps = &rdna2 }), + entry(.project, .decode, "stream", .{ .family = .stream, .fits = &fitsStream, .launch = &launchStream, .policy = &streamOn, .rounds = .always, .round_any = true }), + entry(.project, .decode, "row", .{ .family = .row, .fits = &fitsRow, .launch = &launchRow, .rounds = .fp16 }), + entry(.project, .decode, "lanes", .{ .family = .lanes, .fits = &fitsLanes, .launch = &launchLanes, .rounds = .fp16 }), + entry(.project, .decode, "wide", .{ .family = .wide, .fits = &fitsWide, .launch = &launchWide, .caps = &rdna2 }), + entry(.project, .decode, "matrix", .{ .family = .gemm, .fits = &fitsMatrix, .launch = launchBlock(.matrix), .caps = &matrixCores, .policy = &matrixOn }), + entry(.project, .decode, "gemm", .{ .family = .gemm, .fits = &fitsGemm, .launch = launchBlock(.gemm), .policy = &gemmOn }), + entry(.project, .decode, "block", .{ .family = .gemm, .fits = &fitsBlock, .launch = launchBlock(.block) }), + entry(.project, .decode, "tiled", .{ .family = .tiled, .fits = &fitsTiled, .launch = &launchTiled, .caps = &rdna2 }), + entry(.project, .decode, "reference", .{ .family = .reference, .fits = &fitsReference, .launch = &launchReference, .caps = &rdna2 }), +}; + +const routed_decode = [_]Entry{ + entry(.routed, .decode, "stream", .{ .family = .stream, .fits = &fitsRoutedStream, .launch = &launchStream, .policy = &streamOn }), + entry(.routed, .decode, "row", .{ .family = .row, .fits = &fitsRoutedRow, .launch = &launchRow }), + entry(.routed, .decode, "lanes", .{ .family = .lanes, .fits = &fitsRoutedLanes, .launch = &launchLanes }), + entry(.routed, .decode, "matrix", .{ .family = .gemm, .fits = &fitsRoutedMatrix, .launch = launchBlock(.matrix), .caps = &matrixCores, .policy = &matrixOn }), + entry(.routed, .decode, "gemm", .{ .family = .gemm, .fits = &fitsRoutedGemm, .launch = launchBlock(.gemm), .policy = &gemmOn }), + entry(.routed, .decode, "block", .{ .family = .gemm, .fits = &fitsRoutedBlock, .launch = launchBlock(.block) }), +}; + +const other_decode = [_]Entry{ + entry(.group, .decode, "stream", .{ .family = .stream, .fits = &fitsGroup, .launch = &launchGroup, .policy = &streamOn, .round_any = true }), + entry(.routed_act, .decode, "stream", .{ .family = .stream, .fits = &fitsPair, .launch = &launchPair, .policy = &streamOn }), +}; + +fn prefill(comptime op: Op) [7]Entry { + return .{ + entry(op, .prefill, "kp0", .{ .family = .gemm, .fits = kpFits(0), .launch = launchKp(0), .policy = &gemmOn }), + entry(op, .prefill, "kp1", .{ .family = .gemm, .fits = kpFits(1), .launch = launchKp(1), .policy = &gemmOn }), + entry(op, .prefill, "kp2", .{ .family = .gemm, .fits = kpFits(2), .launch = launchKp(2), .policy = &gemmOn }), + entry(op, .prefill, "kp3", .{ .family = .gemm, .fits = kpFits(3), .launch = launchKp(3), .policy = &gemmOn }), + entry(op, .prefill, "matrix", .{ .family = .gemm, .fits = &fitsPrefillMatrix, .launch = launchBlock(.matrix), .caps = &matrixCores, .policy = &matrixOn }), + entry(op, .prefill, "gemm", .{ .family = .gemm, .fits = &fitsPrefillGemm, .launch = launchBlock(.gemm), .policy = &gemmOn }), + entry(op, .prefill, "block", .{ .family = .gemm, .fits = &fitsPrefillBlock, .launch = launchBlock(.block) }), + }; +} + +pub const all = project_decode ++ routed_decode ++ other_decode ++ prefill(.project) ++ prefill(.routed); + +// ---- the choices on the GPUs' tables + +const Caps = @import("../caps.zig").Caps; + +fn kernelsOn(gfx: []const u8) affine.Registry { + const caps = Caps.of(gfx).?; + return affine.Registry.init(if (caps.generation == .rdna2) &tuning.gfx1030 else &tuning.gfx1100, &all); +} + +fn envOn(gfx: []const u8, stream_on: bool, gemm_on: bool, matrix_on: bool) Env { + const caps = Caps.of(gfx).?; + const matrix = caps.act == .bf16 and caps.matrix == .wmma11; + return .{ .bf16 = caps.act == .bf16, .matrix = matrix, .matrix_on = matrix and matrix_on, .stream_on = stream_on, .gemm_on = gemm_on }; +} + +test "a lane round and a prompt each keep one family at every row count, on every GPU and policy" { + for ([_][]const u8{ "gfx1030", "gfx1100", "gfx1151" }) |gfx| { + const r = kernelsOn(gfx); + for ([_]bool{ true, false }) |matrix_on| try r.verify(envOn(gfx, true, true, matrix_on), .mlx); + } +} + +test "the previous decode tiles take over where the stream tile stops" { + const r = kernelsOn("gfx1030"); + var shape: Shape = .{ .m = 1, .n = 4096, .k = 4096, .bits = 4, .group = 64, .fp16 = true, .tables = .f16 }; + const env = envOn("gfx1030", true, true, false); + // a call outside a lane round: the stream tile to 16 rows, then the wide tile, then the GEMM tile from 64 + const want = [_]struct { u32, []const u8 }{ .{ 1, "stream" }, .{ 16, "stream" }, .{ 17, "wide" }, .{ 63, "wide" }, .{ 64, "gemm" }, .{ 200, "gemm" } }; + for (want) |w| { + shape.m = w[0]; + const e = r.select(env, .mlx, .project, .decode, shape).?; + try std.testing.expect(std.mem.endsWith(u8, e.id, w[1])); + } + // a lane round keeps the stream tile + shape.round = true; + for ([_]u32{ 1, 16, 17, 63, 64, 200 }) |m| { + shape.m = m; + try std.testing.expectEqual(registry.Family.stream, r.select(env, .mlx, .project, .decode, shape).?.family); + } + // the same with the stream tile switched off: the reference tiles by rows + const off = envOn("gfx1030", false, true, false); + shape.m = 4; + try std.testing.expectEqual(registry.Family.lanes, r.select(off, .mlx, .project, .decode, shape).?.family); + shape.m = 1; + try std.testing.expectEqual(registry.Family.row, r.select(off, .mlx, .project, .decode, shape).?.family); +} + +test "the matrix cores take 16 rows and more of a call outside a lane round" { + const r = kernelsOn("gfx1100"); + var shape: Shape = .{ .m = 15, .n = 4096, .k = 4096, .bits = 4, .group = 64, .fp16 = false }; + const on = envOn("gfx1100", true, true, true); + try std.testing.expect(std.mem.endsWith(u8, r.select(on, .mlx, .project, .decode, shape).?.id, "stream")); + shape.m = 16; + try std.testing.expect(std.mem.endsWith(u8, r.select(on, .mlx, .project, .decode, shape).?.id, "matrix")); + const off = envOn("gfx1100", true, true, false); + try std.testing.expect(std.mem.endsWith(u8, r.select(off, .mlx, .project, .decode, shape).?.id, "stream")); + shape.m = 17; + try std.testing.expect(std.mem.endsWith(u8, r.select(off, .mlx, .project, .decode, shape).?.id, "gemm")); + // words the GEMM tile cannot load wide keep the reference tile + shape.words_aligned = false; + try std.testing.expect(std.mem.endsWith(u8, r.select(off, .mlx, .project, .decode, shape).?.id, "block")); +} + +test "a prompt takes the K-parallel tiles by rows and by items, then the 128-row tile" { + const r = kernelsOn("gfx1100"); + const env = envOn("gfx1100", true, true, true); + var shape: Shape = .{ .m = 1, .n = 4096, .k = 4096, .bits = 4, .group = 64, .fp16 = false }; + const plain = [_]struct { u32, []const u8 }{ .{ 1, "kp0" }, .{ 2, "kp0" }, .{ 3, "kp1" }, .{ 4, "kp1" }, .{ 5, "kp2" }, .{ 32, "kp2" }, .{ 33, "matrix" }, .{ 2048, "matrix" } }; + for (plain) |p| { + shape.m = p[0]; + try std.testing.expect(std.mem.endsWith(u8, r.select(env, .mlx, .project, .prefill, shape).?.id, p[1])); + } + shape.items = 100; + shape.m = 30; + try std.testing.expect(std.mem.endsWith(u8, r.select(env, .mlx, .routed, .prefill, shape).?.id, "kp3")); + shape.items = 301; + try std.testing.expect(std.mem.endsWith(u8, r.select(env, .mlx, .routed, .prefill, shape).?.id, "matrix")); + // without the matrix cores the dot2 GEMM tile + shape.items = 0; + shape.m = 64; + try std.testing.expect(std.mem.endsWith(u8, r.select(envOn("gfx1100", true, true, false), .mlx, .project, .prefill, shape).?.id, "gemm")); + // RDNA2 takes a plan of up to 410 items on the second K-parallel tile + const v = kernelsOn("gfx1030"); + shape.fp16 = true; + shape.items = 350; + shape.m = 10; + try std.testing.expect(std.mem.endsWith(u8, v.select(envOn("gfx1030", true, true, false), .mlx, .routed, .prefill, shape).?.id, "kp1")); +} diff --git a/zig/src/hip/launches/moe.zig b/zig/src/hip/launches/moe.zig new file mode 100644 index 00000000000..c998a43b094 --- /dev/null +++ b/zig/src/hip/launches/moe.zig @@ -0,0 +1,122 @@ +//! MoE launches: router, select, plan, activation and combine. + +const Launcher = @import("../launches.zig").Launcher; +const util = @import("util.zig"); +const S = util.S; +const P = util.P; +const C = util.C; +const F = util.F; +const I = util.I; +const CF = util.CF; +const CI = util.CI; +const Args = util.Args; +const Error = util.Error; +const ad = util.ad; +const dim = util.dim; +const cdiv = util.cdiv; +const tri = util.tri; +const invalid = util.invalid; + +/// The most rows the router's wave-an-expert kernel takes in prefill. +pub const router_small_rows = 32; + +/// The router's logits at any row count so prompt rows ignore cuts: 64 x 64 tiles, or a wave an expert, same bits. +pub fn routerTile(l: *const Launcher, x: C, kind: c_int, rows: CF, logits: F, r: c_int, d: c_int, e: c_int, s: S) Error!void { + return routerWith(l, x, kind, rows, logits, r, d, e, s, r <= router_small_rows); +} + +pub fn routerWith(l: *const Launcher, x: C, kind: c_int, rows: CF, logits: F, r: c_int, d: c_int, e: c_int, s: S, small: bool) Error!void { + var a: Args = .{}; + try a.add(ad(x)); + try a.add(ad(rows)); + try a.add(ad(logits)); + try a.add(r); + try a.add(d); + try a.add(e); + const k: usize = if (kind == 1) 0 else 1; + if (small) return l.go(l.op.router_small[k], dim(cdiv(e, 8), cdiv(r, 32), 1), dim(256, 1, 1), 0, s, &a); + try l.go(l.op.router_tile[k], dim(cdiv(e, 64), cdiv(r, 64), 1), dim(256, 1, 1), 0, s, &a); +} + +/// A lane round's router at any row count; false (nothing launched) where the shape keeps the other kernels. +pub fn routerWindow(l: *const Launcher, x: C, kind: c_int, rows: CF, logits: F, r: c_int, d: c_int, e: c_int, s: S) Error!bool { + if (!l.fuse or r < 1 or @rem(d, 4) != 0 or ad(rows) % 16 != 0 or ad(x) % 8 != 0) return false; + var a: Args = .{}; + try a.add(ad(x)); + try a.add(ad(rows)); + try a.add(ad(logits)); + try a.add(r); + try a.add(d); + try a.add(e); + try l.go(l.dec.router[if (kind == 1) 0 else 1], dim(cdiv(e, 4), cdiv(r, 16), 1), dim(128, 1, 1), 0, s, &a); + return true; +} + +pub fn tf_moe_router(l: *const Launcher, x: C, kind: c_int, rows: CF, logits: F, r: c_int, d: c_int, e: c_int, s: S) Error!void { + // a prompt's rows take the 64 x 64 tiles, a round's few rows a wave an expert; each logit's sum is the same + var a: Args = .{}; + try a.add(ad(x)); + try a.add(ad(rows)); + try a.add(ad(logits)); + try a.add(r); + try a.add(d); + try a.add(e); + const k: usize = if (kind == 1) 0 else 1; + if (l.fuse and r <= 16 and @rem(d, 4) == 0 and ad(rows) % 16 == 0 and ad(x) % 8 == 0) { + return l.go(l.dec.router[k], dim(cdiv(e, 4), 1, 1), dim(128, 1, 1), 0, s, &a); + } + if (r >= 64 and @rem(d, 32) == 0) return l.go(l.op.router_tile[k], dim(cdiv(e, 64), cdiv(r, 64), 1), dim(256, 1, 1), 0, s, &a); + try l.go(l.op.router_rows[k], dim(cdiv(e, 8), cdiv(r, 8), 1), dim(256, 1, 1), 0, s, &a); +} + +pub fn tf_moe_select(l: *const Launcher, logits: CF, pick: I, wts: F, items: I, members: I, capacity: c_int, r: c_int, experts: c_int, top_k: c_int, s: S) Error!void { + if (experts > 1024 or top_k < 1 or top_k > 31) return invalid("moe select"); + var a: Args = .{}; + try a.add(ad(logits)); + try a.add(ad(pick)); + try a.add(ad(wts)); + try a.add(ad(items)); + try a.add(ad(members)); + try a.add(capacity); + try a.add(experts); + try a.add(top_k); + if (l.fuse) return l.go(l.dec.select, dim(r, 1, 1), dim(256, 1, 1), 0, s, &a); + try l.go(l.moe_select, dim(r, 1, 1), dim(32, 1, 1), 0, s, &a); +} + +pub fn tf_moe_act(l: *const Launcher, both: CF, out: P, kind: c_int, pairs: c_int, width: c_int, limit: f32, s: S) Error!void { + const total = @as(i64, pairs) * width; + var a: Args = .{}; + try a.add(ad(both)); + try a.add(ad(out)); + try a.add(width); + try a.add(limit); + try a.add(total); + try l.go(l.moe_act[if (kind == 1) 0 else 1], dim(cdiv(total, 256), 1, 1), dim(256, 1, 1), 0, s, &a); +} + +pub fn tf_moe_combine(l: *const Launcher, y: CF, wts: CF, out: P, kind: c_int, r: c_int, slots: c_int, d: c_int, s: S) Error!void { + var a: Args = .{}; + try a.add(ad(y)); + try a.add(ad(wts)); + try a.add(ad(out)); + try a.add(slots); + try a.add(d); + try l.go(l.moe_combine[tri(kind)], dim(cdiv(d, 256), r, 1), dim(256, 1, 1), 0, s, &a); +} + +pub fn tf_moe_route(l: *const Launcher, picks: CI, pairs: c_int, experts: c_int, tile: c_int, members: I, items: I, capacity: c_int, s: S) Error!void { + var a: Args = .{}; + try a.add(ad(picks)); + try a.add(pairs); + try a.add(experts); + try a.add(tile); + try a.add(ad(members)); + try a.add(ad(items)); + try a.add(capacity); + // every expert's count, start and end, and each pair segment's 16-bit counts, in dynamic shared memory + const ex: usize = @intCast(experts); + const segs: usize = if (ex <= 256) 64 else 16; + if (ex > 1024) return invalid("moe_route"); + try l.go(l.op.moe_route, dim(1, 1, 1), dim(256, 1, 1), @intCast(3 * ex * 4 + segs * ex * 2), s, &a); +} diff --git a/zig/src/hip/launches/norms.zig b/zig/src/hip/launches/norms.zig new file mode 100644 index 00000000000..ca9a007c56c --- /dev/null +++ b/zig/src/hip/launches/norms.zig @@ -0,0 +1,83 @@ +//! Norm launches and the decode tails that fuse a norm. + +const Launcher = @import("../launches.zig").Launcher; +const util = @import("util.zig"); +const S = util.S; +const P = util.P; +const C = util.C; +const F = util.F; +const CF = util.CF; +const Args = util.Args; +const Error = util.Error; +const ad = util.ad; +const dim = util.dim; +const cdiv = util.cdiv; +const tri = util.tri; +const invalid = util.invalid; + +pub fn tf_rms(l: *const Launcher, x: C, weight: CF, y: P, kind: c_int, rows: c_int, width: c_int, eps: f32, s: S) Error!void { + var a: Args = .{}; + try a.add(ad(x)); + if (width <= 1024) { + // a wave a row, rms_kernel's sums + try a.add(kind); + try a.add(ad(weight)); + try a.add(ad(y)); + try a.add(rows); + try a.add(width); + try a.add(eps); + return l.go(l.op.rms_rows, dim(cdiv(rows, 8), 1, 1), dim(256, 1, 1), 0, s, &a); + } + try a.add(ad(weight)); + try a.add(ad(y)); + try a.add(width); + try a.add(eps); + try l.go(l.rms[tri(kind)], dim(rows, 1, 1), dim(256, 1, 1), 0, s, &a); +} + +/// Two sets of fp32 rows of `width` (at most 1024), each with its own weight, normed in one launch. +pub fn tf_rms2(l: *const Launcher, x0: CF, w0: CF, y0: F, x1: CF, w1: CF, y1: F, rows: c_int, width: c_int, eps: f32, s: S) Error!void { + if (width > 1024) return invalid("rms2"); + var a: Args = .{}; + try a.add(ad(x0)); + try a.add(ad(w0)); + try a.add(ad(y0)); + try a.add(ad(x1)); + try a.add(ad(w1)); + try a.add(ad(y1)); + try a.add(rows); + try a.add(width); + try a.add(eps); + try l.go(l.dec.rms2, dim(cdiv(rows, 8), 2, 1), dim(256, 1, 1), 0, s, &a); +} + +/// out = rms(y) * weight * round(silu(z)) rounded to the kind, rows of `width` (at most 1024). +pub fn tf_gnorm_out(l: *const Launcher, y: CF, weight: CF, z: C, out: P, kind: c_int, rows: c_int, width: c_int, eps: f32, s: S) Error!void { + if (width > 1024) return invalid("gnorm out"); + var a: Args = .{}; + try a.add(ad(y)); + try a.add(ad(weight)); + try a.add(ad(z)); + try a.add(ad(out)); + try a.add(kind); + try a.add(rows); + try a.add(width); + try a.add(eps); + try l.go(l.dec.gnorm_out, dim(cdiv(rows, 8), 1, 1), dim(256, 1, 1), 0, s, &a); +} + +/// x = round(x + t), t being y or the weighted sum of the row's `slots`; normed = rms(x) * weight, a block a row. +pub fn tf_tail(l: *const Launcher, x: P, y: C, wts: CF, weight: CF, normed: P, kind: c_int, rows: c_int, slots: c_int, width: c_int, eps: f32, s: S) Error!void { + if (width > 8192 or rows < 1) return invalid("tail"); + var a: Args = .{}; + try a.add(ad(x)); + try a.add(ad(y)); + try a.add(ad(wts)); + try a.add(ad(weight)); + try a.add(ad(normed)); + try a.add(kind); + try a.add(slots); + try a.add(width); + try a.add(eps); + try l.go(l.dec.tail, dim(rows, 1, 1), dim(512, 1, 1), 0, s, &a); +} diff --git a/zig/src/hip/launches/plan.zig b/zig/src/hip/launches/plan.zig new file mode 100644 index 00000000000..2a7b0bb3b59 --- /dev/null +++ b/zig/src/hip/launches/plan.zig @@ -0,0 +1,188 @@ +//! A lane round's launches over its device plan: cache writes, the attention walk, the recurrence and the keep. + +const Launcher = @import("../launches.zig").Launcher; +const util = @import("util.zig"); +const S = util.S; +const Args = util.Args; +const Error = util.Error; +const dim = util.dim; +const cdiv = util.cdiv; +const invalid = util.invalid; + +/// plan.hpp's PlanArgs: device addresses of the round's per-row and per-slot arrays (all zero: no plan). +pub const PlanArgs = extern struct { + pos: u64 = 0, + slot: u64 = 0, + first: u64 = 0, + count: u64 = 0, + desc: u64 = 0, + snaps: u64 = 0, + pages: u32 = 0, + pool: u32 = 0, +}; + +/// A plan's shape: `rows` rows (a bucket, padding included) over `slots` slots. +pub const PlanRef = struct { args: PlanArgs, rows: usize, slots: usize }; + +/// Rows of keys (fp32, rotated) and values (fp16 or bf16) into each row's slot at its position. +pub fn planKvWrite(l: *const Launcher, keys: u64, values: u64, kind: c_int, p: PlanRef, layer: usize, kv_heads: usize, d: usize, s: S) Error!void { + var a: Args = .{}; + try a.add(keys); + try a.add(values); + try a.add(kind); + try a.add(@as(c_int, @intCast(p.rows))); + try a.add(@as(c_int, @intCast(kv_heads))); + try a.add(@as(c_int, @intCast(d))); + try a.add(p.args); + try a.add(@as(c_int, @intCast(layer))); + try l.flat(l.plan.kv_write, @intCast(p.rows * kv_heads * d), s, &a); +} + +/// One query a row (rows, heads, d) fp32 over its slot's caches up to its position; the walk covers `span` keys. +pub fn planCausal(l: *const Launcher, q: u64, out: u64, scores: u64, stats: u64, partials: u64, p: PlanRef, layer: usize, heads: usize, kv_heads: usize, d: usize, span: usize, scale: f32, kind: c_int, s: S) Error!void { + if (d > 256 or heads < 1 or kv_heads < 1 or @rem(heads, kv_heads) != 0 or kind < 1 or kind > 2) return invalid("planned attention"); + const which: usize = @intCast(kind - 1); + const rows = p.rows; + const tiles: c_int = @intCast(cdiv(span, 128)); + const span_c: c_int = @intCast(span); + const heads_c: c_int = @intCast(heads); + const kv_c: c_int = @intCast(kv_heads); + const d_c: c_int = @intCast(d); + const layer_c: c_int = @intCast(layer); + // a block takes `group` query heads of one KV head (at most plan.hip's kMaxGroup): the cache is read once for them + var group = @divExact(heads, kv_heads); + while (group > 16) group = @divExact(group, smallestFactor(group)); + const blocks = @divExact(heads, group); + var a: Args = .{}; + try a.add(q); + try a.add(scores); + try a.add(span_c); + try a.add(heads_c); + try a.add(kv_c); + try a.add(d_c); + try a.add(scale); + try a.add(p.args); + try a.add(layer_c); + // a warp scores a key for the block's heads: four warps a block, the heads' queries in shared memory + try l.go(l.plan.score[which], dim(cdiv(span, 4), blocks, rows), dim(128, 1, 1), @intCast(group * d * 4), s, &a); + var b: Args = .{}; + try b.add(scores); + try b.add(stats); + try b.add(span_c); + try b.add(@as(c_int, 0)); + try b.add(p.args.pos); + try l.go(l.softmax_stats, dim(heads, rows, 1), dim(256, 1, 1), 0, s, &b); + var c: Args = .{}; + try c.add(scores); + try c.add(stats); + try c.add(partials); + try c.add(span_c); + try c.add(heads_c); + try c.add(kv_c); + try c.add(d_c); + try c.add(p.args); + try c.add(layer_c); + try l.go(l.plan.apply[which], dim(tiles, blocks, rows), dim(256, 1, 1), 0, s, &c); + var e: Args = .{}; + try e.add(partials); + try e.add(out); + try e.add(tiles); + try e.add(d_c); + try l.go(l.sum_partials, dim(heads, rows, 1), dim(256, 1, 1), 0, s, &e); +} + +fn smallestFactor(n: usize) usize { + var f: usize = 2; + while (@rem(n, f) != 0) f += 1; + return f; +} + +/// The DeltaNet recurrence of every slot's rows (q, k, v, gate, beta, y flat over rows), state in the slot's caches. +pub fn planGatedDelta(l: *const Launcher, q: u64, k: u64, v: u64, gate: u64, beta: u64, y: u64, p: PlanRef, layer: usize, key_heads: usize, value_heads: usize, dk: usize, dv: usize, s: S) Error!void { + if ((dk != 16 and dk != 128) or @rem(dv, 8) != 0 or key_heads < 1 or @rem(value_heads, key_heads) != 0) return invalid("planned gated delta"); + var a: Args = .{}; + try a.add(q); + try a.add(k); + try a.add(v); + try a.add(gate); + try a.add(beta); + try a.add(y); + try a.add(@as(c_int, @intCast(key_heads))); + try a.add(@as(c_int, @intCast(value_heads))); + try a.add(@as(c_int, @intCast(dv))); + try a.add(p.args); + try a.add(@as(c_int, @intCast(layer))); + const wide: usize = if (dk == 128) 0 else 1; + try l.go(l.plan.gdn[wide], dim(@divExact(dv, 8), value_heads, p.slots), dim(32, 8, 1), 0, s, &a); +} + +/// Row r of `dst` (`words` words each) from the address in `srcs[r]` (device u64s), for `rows` rows. +pub fn planGather(l: *const Launcher, srcs: u64, dst: u64, words: usize, rows: usize, s: S) Error!void { + if (words % 4 != 0 or rows == 0) return invalid("planned gather"); + var a: Args = .{}; + try a.add(srcs); + try a.add(dst); + try a.add(@as(c_int, @intCast(words))); + try l.go(l.plan.gather, dim(cdiv(words, 256), rows, 1), dim(256, 1, 1), 0, s, &a); +} + +/// Writes positions pos0 .. pos0 + len of a stream's pages from 16-bit `src` at h * s_head + r * s_row + j. +pub fn pagesWrite(l: *const Launcher, src: u64, pool: u64, table: u64, len: usize, kv_heads: usize, d: usize, s_head: usize, s_row: usize, pos0: usize, count: usize, s: S) Error!void { + var a: Args = .{}; + try a.add(src); + try a.add(pool); + try a.add(table); + try a.add(@as(c_int, @intCast(len))); + try a.add(@as(c_int, @intCast(kv_heads))); + try a.add(@as(c_int, @intCast(d))); + try a.add(@as(c_longlong, @intCast(s_head))); + try a.add(@as(c_longlong, @intCast(s_row))); + try a.add(@as(c_int, @intCast(pos0))); + try a.add(@as(c_int, @intCast(count))); + try l.flat(l.plan.page_write, @intCast(len * kv_heads * d), s, &a); +} + +/// The first `len` positions of a stream's pages as (kv_heads, len, d) 16-bit values in `dst`. +pub fn pagesGather(l: *const Launcher, pool: u64, table: u64, dst: u64, len: usize, kv_heads: usize, d: usize, count: usize, s: S) Error!void { + var a: Args = .{}; + try a.add(pool); + try a.add(table); + try a.add(dst); + try a.add(@as(c_int, @intCast(len))); + try a.add(@as(c_int, @intCast(kv_heads))); + try a.add(@as(c_int, @intCast(d))); + try a.add(@as(c_int, @intCast(count))); + try l.flat(l.plan.page_gather, @intCast(len * kv_heads * d), s, &a); +} + +/// What a keep reads: the plan, kept rows a slot (negative: unlisted), final rows, word counts (of four), layers. +pub const Keep = struct { keep: u64, hidden: u64, hidden_words: usize, channels: usize, taps: usize, layers: usize }; + +/// Keeps the listed slots' rows: conv windows from the round's first window and the kept rows' inputs, final rows. +pub fn planKeep(l: *const Launcher, p: PlanRef, k: Keep, s: S) Error!void { + if (k.hidden_words % 4 != 0) return invalid("planned keep"); + var a: Args = .{}; + try a.add(p.args); + try a.add(k.keep); + try a.add(k.hidden); + try a.add(@as(c_int, @intCast(k.hidden_words))); + try a.add(@as(c_int, @intCast(k.channels))); + try a.add(@as(c_int, @intCast(k.taps))); + try a.add(@as(c_int, @intCast(k.layers))); + try l.go(l.plan.keep, dim(64, k.layers + 1, p.slots), dim(256, 1, 1), 0, s, &a); +} + +/// The kept slots' DeltaNet states run through their kept rows, every linear layer in one launch. +pub fn planGdnReplay(l: *const Launcher, keep: u64, p: PlanRef, key_heads: usize, value_heads: usize, dk: usize, dv: usize, layers: usize, s: S) Error!void { + if ((dk != 16 and dk != 128) or @rem(dv, 8) != 0 or key_heads < 1 or @rem(value_heads, key_heads) != 0) return invalid("planned replay"); + var a: Args = .{}; + try a.add(keep); + try a.add(@as(c_int, @intCast(p.rows))); + try a.add(@as(c_int, @intCast(key_heads))); + try a.add(@as(c_int, @intCast(value_heads))); + try a.add(@as(c_int, @intCast(dv))); + try a.add(p.args); + try a.add(@as(c_int, @intCast(p.slots))); + const wide: usize = if (dk == 128) 0 else 1; + try l.go(l.plan.gdn_replay[wide], dim(@divExact(dv, 8), value_heads, p.slots * layers), dim(32, 8, 1), 0, s, &a); +} diff --git a/zig/src/hip/launches/recurrence.zig b/zig/src/hip/launches/recurrence.zig new file mode 100644 index 00000000000..a654d56a2bb --- /dev/null +++ b/zig/src/hip/launches/recurrence.zig @@ -0,0 +1,79 @@ +//! DeltaNet launches: gate, recurrence and the gated norm. + +const Launcher = @import("../launches.zig").Launcher; +const util = @import("util.zig"); +const S = util.S; +const P = util.P; +const C = util.C; +const F = util.F; +const CF = util.CF; +const Args = util.Args; +const Error = util.Error; +const ad = util.ad; +const dim = util.dim; +const cdiv = util.cdiv; +const tri = util.tri; +const invalid = util.invalid; + +pub fn tf_gdn_gate(l: *const Launcher, av: C, bv: C, kind: c_int, a_log: CF, dt_bias: CF, gate: F, beta: F, count: c_int, heads: c_int, s: S) Error!void { + var a: Args = .{}; + try a.add(ad(av)); + try a.add(ad(bv)); + try a.add(ad(a_log)); + try a.add(ad(dt_bias)); + try a.add(ad(gate)); + try a.add(ad(beta)); + try a.add(count); + try a.add(heads); + try l.go(l.gdn_gate[tri(kind)], dim(cdiv(count, 256), 1, 1), dim(256, 1, 1), 0, s, &a); +} + +pub fn tf_gated_delta(l: *const Launcher, q: CF, k: CF, v: CF, gate: CF, beta: CF, state: F, y: F, batch: c_int, length: c_int, key_heads: c_int, value_heads: c_int, dk: c_int, dv: c_int, s: S, states: F) Error!void { + if ((dk != 16 and dk != 128) or dv < 1 or key_heads < 1 or @rem(value_heads, key_heads) != 0 or batch < 1 or length < 1) { + return invalid("gated delta"); + } + var a: Args = .{}; + try a.add(ad(q)); + try a.add(ad(k)); + try a.add(ad(v)); + try a.add(ad(gate)); + try a.add(ad(beta)); + try a.add(ad(state)); + try a.add(ad(y)); + try a.add(length); + try a.add(key_heads); + try a.add(value_heads); + try a.add(dv); + try a.add(ad(states)); + const wide: usize = if (dk == 128) 0 else 1; + // Eight rows share one k/q tile; a short dv stays on the one-row wave, which is the same scan. + if (@rem(dv, 8) == 0) { + try l.go(l.gated_delta_tile[wide], dim(@divExact(dv, 8), value_heads, batch), dim(32, 8, 1), 0, s, &a); + } else { + try l.go(l.gated_delta_wave[wide], dim(dv, value_heads, batch), dim(32, 1, 1), 0, s, &a); + } +} + +pub fn tf_gdn_gate_prefill(l: *const Launcher, av: C, bv: C, kind: c_int, a_log: CF, dt_bias: CF, gate: F, beta: F, count: c_int, heads: c_int, s: S) Error!void { + var a: Args = .{}; + try a.add(ad(av)); + try a.add(ad(bv)); + try a.add(kind); + try a.add(ad(a_log)); + try a.add(ad(dt_bias)); + try a.add(ad(gate)); + try a.add(ad(beta)); + try a.add(count); + try a.add(heads); + try l.flat(l.op.gdn_gate_prefill, @as(i64, count) * heads, s, &a); +} + +pub fn tf_gnorm_silu(l: *const Launcher, y: CF, z: C, out: P, kind: c_int, n: c_longlong, s: S) Error!void { + var a: Args = .{}; + try a.add(ad(y)); + try a.add(ad(z)); + try a.add(ad(out)); + try a.add(kind); + try a.add(n); + try l.flat(l.op.gnorm_silu, n, s, &a); +} diff --git a/zig/src/hip/launches/rope.zig b/zig/src/hip/launches/rope.zig new file mode 100644 index 00000000000..69ec48c0fd0 --- /dev/null +++ b/zig/src/hip/launches/rope.zig @@ -0,0 +1,68 @@ +//! RoPE launches: decode, prefill and the window's fused q / k norm and rotation. + +const Launcher = @import("../launches.zig").Launcher; +const util = @import("util.zig"); +const S = util.S; +const P = util.P; +const C = util.C; +const F = util.F; +const CF = util.CF; +const CI = util.CI; +const Args = util.Args; +const Error = util.Error; +const ad = util.ad; +const dim = util.dim; +const cdiv = util.cdiv; +const invalid = util.invalid; + +pub fn tf_qk_rope(l: *const Launcher, src: C, kind: c_int, s_row: c_longlong, s_head: c_int, weight: CF, eps: f32, rows: c_int, heads: c_int, width: c_int, rotary: c_int, theta: f32, pos: CI, wide: F, cache: P, total: c_int, s: S) Error!void { + if (width > 512) return invalid("qk_rope"); + var a: Args = .{}; + try a.add(ad(src)); + try a.add(kind); + try a.add(s_row); + try a.add(s_head); + try a.add(ad(weight)); + try a.add(eps); + try a.add(rows); + try a.add(heads); + try a.add(width); + try a.add(rotary); + try a.add(theta); + try a.add(ad(pos)); + try a.add(ad(wide)); + try a.add(ad(cache)); + try a.add(total); + // a wave a (row, head), 8 a block + try l.go(l.op.qk_rope, dim(cdiv(@as(i64, rows) * heads, 8), 1, 1), dim(256, 1, 1), 0, s, &a); +} + +pub fn tf_rope_decode(l: *const Launcher, x: CF, y: F, rows: c_int, width: c_int, rotary: c_int, pos: c_int, theta: f32, s: S, pos_dev: CI, per: c_int) Error!void { + var a: Args = .{}; + try a.add(ad(x)); + try a.add(ad(y)); + try a.add(width); + try a.add(rotary); + try a.add(pos); + try a.add(theta); + try a.add(ad(pos_dev)); + try a.add(per); + try l.go(l.rope_decode, dim(rows, 1, 1), dim(32, 1, 1), 0, s, &a); +} + +pub fn tf_rope_prefill(l: *const Launcher, x: C, kind: c_int, out: P, out_kind: c_int, s_head: c_longlong, s_row: c_longlong, len: c_int, heads: c_int, d: c_int, rotary: c_int, pos0: c_int, theta: f32, s: S) Error!void { + var a: Args = .{}; + try a.add(ad(x)); + try a.add(kind); + try a.add(ad(out)); + try a.add(out_kind); + try a.add(s_head); + try a.add(s_row); + try a.add(len); + try a.add(heads); + try a.add(d); + try a.add(rotary); + try a.add(pos0); + try a.add(theta); + try l.flat(l.op.rope_prefill, @as(i64, len) * heads * d, s, &a); +} diff --git a/zig/src/hip/launches/tp.zig b/zig/src/hip/launches/tp.zig new file mode 100644 index 00000000000..f4f6d85f7b5 --- /dev/null +++ b/zig/src/hip/launches/tp.zig @@ -0,0 +1,77 @@ +//! A tensor-parallel rank's launches (the fp32 sum into a residual, the local expert ids) and MTP's token probability. + +const Launcher = @import("../launches.zig").Launcher; +const util = @import("util.zig"); +const S = util.S; +const C = util.C; +const P = util.P; +const I = util.I; +const CI = util.CI; +const F = util.F; +const CF = util.CF; +const Args = util.Args; +const Error = util.Error; +const ad = util.ad; +const dim = util.dim; + +fn blocks(n: i64, threads: i64) c_int { + return @intCast(@divFloor(n + threads - 1, threads)); +} + +/// out = round(x + y) of `n` values, x and out of `kind` (1 fp16, 2 bf16), y fp32. +pub fn tf_add_wide(l: *const Launcher, x: C, y: CF, out: P, kind: c_int, n: c_longlong, s: S) Error!void { + if (n == 0) return; + var a: Args = .{}; + try a.add(ad(x)); + try a.add(ad(y)); + try a.add(ad(out)); + try a.add(kind); + try a.add(n); + try l.go(l.op.add_wide, dim(blocks(n, 256), 1, 1), dim(256, 1, 1), 0, s, &a); +} + +/// out[i] = remap[pick[i]], or `skip` where it is negative. +pub fn tf_moe_localize(l: *const Launcher, pick: CI, remap: CI, out: I, n: c_int, skip: c_int, s: S) Error!void { + if (n == 0) return; + var a: Args = .{}; + try a.add(ad(pick)); + try a.add(ad(remap)); + try a.add(ad(out)); + try a.add(n); + try a.add(skip); + try l.go(l.op.moe_localize, dim(blocks(n, 256), 1, 1), dim(256, 1, 1), 0, s, &a); +} + +/// Zeroes the pair count of every plan item of the `skip` expert. +pub fn tf_moe_foreign_items(l: *const Launcher, items: I, count: c_int, skip: c_int, s: S) Error!void { + if (count == 0) return; + var a: Args = .{}; + try a.add(ad(items)); + try a.add(count); + try a.add(skip); + try l.go(l.op.moe_foreign_items, dim(blocks(count, 256), 1, 1), dim(256, 1, 1), 0, s, &a); +} + +/// Zeroes the rows of `y` (pairs, d) fp32 whose pick is `skip`. +pub fn tf_moe_zero_foreign(l: *const Launcher, y: F, picks: CI, skip: c_int, pairs: c_longlong, d: c_int, s: S) Error!void { + if (pairs == 0) return; + var a: Args = .{}; + try a.add(ad(y)); + try a.add(ad(picks)); + try a.add(skip); + try a.add(pairs); + try a.add(d); + try l.go(l.op.moe_zero_foreign, dim(blocks(pairs * d, 256), 1, 1), dim(256, 1, 1), 0, s, &a); +} + +/// out[r] = softmax(row r)[id[r]] of (rows, n) logits of `kind`, or of the row's largest value when `id` is null. +pub fn tf_token_prob(l: *const Launcher, logits: C, kind: c_int, rows: c_int, n: c_int, id: CI, out: F, s: S) Error!void { + if (rows == 0) return; + var a: Args = .{}; + try a.add(ad(logits)); + try a.add(kind); + try a.add(n); + try a.add(ad(id)); + try a.add(ad(out)); + try l.go(l.op.token_prob, dim(rows, 1, 1), dim(256, 1, 1), 0, s, &a); +} diff --git a/zig/src/hip/launches/util.zig b/zig/src/hip/launches/util.zig new file mode 100644 index 00000000000..ffa49027728 --- /dev/null +++ b/zig/src/hip/launches/util.zig @@ -0,0 +1,49 @@ +//! The launchers' shared shorthand: argument types, device addresses and grid arithmetic. + +const std = @import("std"); +const abi = @import("../abi.zig"); +const runtime = @import("../runtime.zig"); +const launch = @import("../launch.zig"); +const Function = @import("../module.zig").Function; + +pub const Error = runtime.Error; + +/// A stream handle; `counting` launches nothing, so a dry run measures the scratch a forward takes. +pub const S = abi.Stream; +pub const counting: S = @ptrFromInt(0x1); +pub const P = ?*anyopaque; +pub const C = ?*const anyopaque; +pub const F = ?[*]f32; +pub const CF = ?[*]const f32; +pub const I = ?[*]i32; +pub const CI = ?[*]const i32; + +pub const Dim3 = launch.Dim3; +pub const Args = launch.Args; + +/// A device address as the kernel argument it is. +pub fn ad(p: anytype) u64 { + return @intFromPtr(p); +} + +pub fn dim(x: anytype, y: anytype, z: anytype) Dim3 { + return .{ .x = @intCast(x), .y = @intCast(y), .z = @intCast(z) }; +} + +/// ceil(n / by) as a grid extent. +pub fn cdiv(n: anytype, by: anytype) usize { + return (@as(usize, @intCast(n)) + by - 1) / by; +} + +/// The kernel of a triple for an activation kind: fp16 and bf16 by number, anything else the first. +pub fn tri(kind: c_int) usize { + return if (kind == 1 or kind == 2) @intCast(kind) else 0; +} + +/// By kind (0 fp32, 1 fp16, 2 bf16) or by cache kind (0 fp16, 1 bf16, 2 fp32), the kernel one instantiation. +pub const Triple = [3]Function; + +pub fn invalid(what: []const u8) Error { + std.log.err("{s}: shape", .{what}); + return error.Invalid; +} diff --git a/zig/src/hip/memory.zig b/zig/src/hip/memory.zig index 9c3dd094f41..7857623c9ec 100644 --- a/zig/src/hip/memory.zig +++ b/zig/src/hip/memory.zig @@ -61,6 +61,11 @@ pub const DeviceBuffer = struct { self.* = undefined; } + /// The device address of the first byte, as kernel arguments take it. + pub fn base(self: DeviceBuffer) u64 { + return @intFromPtr(self.ptr); + } + /// 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; @@ -171,6 +176,17 @@ pub const HostBuffer = struct { return @intFromPtr(ptr); } + /// Bytes `from..to` of this buffer, still pinned, for an async copy of part of it. + pub fn view(self: HostBuffer, from: usize, to: usize) HostBuffer { + return .{ .r = self.r, .bytes = self.bytes[from..to] }; + } + + /// The bytes as `T`s, the tail that does not fill one left out. + pub fn slice(self: HostBuffer, comptime T: type) []T { + const whole = self.bytes[0 .. self.bytes.len / @sizeOf(T) * @sizeOf(T)]; + return @alignCast(std.mem.bytesAsSlice(T, @as([]align(@alignOf(T)) u8, @alignCast(whole)))); + } + /// All streams using these bytes must have completed before release. pub fn free(self: *HostBuffer) void { _ = self.r.api.hipHostFree(self.bytes.ptr); diff --git a/zig/src/hip/ops/attention.zig b/zig/src/hip/ops/attention.zig new file mode 100644 index 00000000000..7e356c4e4cf --- /dev/null +++ b/zig/src/hip/ops/attention.zig @@ -0,0 +1,87 @@ +//! Attention launches: the gate, RoPE, cache writes and the causal kernels over a cache. + +const t = @import("types.zig"); +const Ops = @import("ops.zig").Ops; +const Error = t.Error; +const Tensor = t.Tensor; +const Kind = t.Kind; +const p = t.p; +const f = t.f; +const int = t.int; + +/// The gated attention's o input from att fp32, (heads, len, d) or (len, heads, d) with `rows_major`, and the gate. +pub fn attnGate(o: Ops, att: u64, qg: Tensor, out: Tensor, len: usize, heads: usize, d: usize, rows_major: bool) Error!void { + try o.l.tf_attn_gate(f(att), p(qg.ptr), p(out.ptr), @backingInt(out.kind), int(len), int(heads), int(d), @intFromBool(rows_major), o.stream); +} + +/// Prefill RoPE of x (len, heads, d), rounded to x's kind, stored as `out` kind at out[h * s_head + r * s_row + j]. +pub fn ropePrefill(o: Ops, x: Tensor, out: Tensor, s_head: usize, s_row: usize, len: usize, heads: usize, d: usize, rotary: usize, pos0: usize, theta: f32) Error!void { + try o.l.tf_rope_prefill(p(x.ptr), @backingInt(x.kind), p(out.ptr), @backingInt(out.kind), @intCast(s_head), @intCast(s_row), int(len), int(heads), int(d), int(rotary), int(pos0), theta, o.stream); +} + +/// A window's q or k heads RMS-normed with `weight`, rotated at `pos`, rounded; into fp32 `wide` and/or cache slots. +pub fn qkRope(o: Ops, src: Tensor, s_row: usize, s_head: usize, weight: u64, eps: f32, rows: usize, heads: usize, width: usize, rotary: usize, theta: f32, pos: u64, wide: ?u64, cache: ?u64, total: usize) Error!void { + if (width > 512 or src.kind == .f32) return error.BadShape; + try o.l.tf_qk_rope(p(src.ptr), @backingInt(src.kind), @intCast(s_row), int(s_head), f(weight), eps, int(rows), int(heads), int(width), int(rotary), theta, @ptrFromInt(pos), if (wide) |w| f(w) else null, if (cache) |c| p(c) else null, int(total), o.stream); +} + +/// The decode RoPE over fp32 rows; `pos_dev` (int32, one a group of `per` rows) or the host `pos`. +pub fn ropeDecode(o: Ops, x: u64, y: u64, rows: usize, width: usize, rotary: usize, pos: usize, theta: f32, pos_dev: ?u64, per: usize) Error!void { + try o.l.tf_rope_decode(f(x), f(y), int(rows), int(width), int(rotary), int(pos), theta, o.stream, if (pos_dev) |a| @ptrFromInt(a) else null, int(per)); +} + +pub fn kvWrite(o: Ops, src: Tensor, cache: u64, len: usize, kv_heads: usize, d: usize, total: usize, pos0: usize) Error!void { + try o.l.tf_kv_write(p(src.ptr), p(cache), @backingInt(src.kind), int(len), int(kv_heads), int(d), int(total), int(pos0), o.stream); +} + +/// kv_write with the first slot read from the device (one int32), for graphs replayed at new positions. +pub fn kvWriteAt(o: Ops, src: Tensor, cache: u64, len: usize, kv_heads: usize, d: usize, total: usize, pos: u64) Error!void { + try o.l.tf_kv_write_at(p(src.ptr), p(cache), @backingInt(src.kind), int(len), int(kv_heads), int(d), int(total), @ptrFromInt(pos), o.stream); +} + +/// The cache's layout: `kv_heads` heads of `total` slots of `d` values (batch 1). +pub const Cache = struct { k: u64, v: u64, kind: Kind, kv_heads: usize, total: usize, d: usize }; + +/// Prefill attention on the prefill tile (any query count): q (heads, qlen, d) fp32 over the first `span` slots. +pub fn causalPrefill(o: Ops, q: u64, c: Cache, out: u64, qlen: usize, span: usize, heads: usize, scale: f32, q_pos0: usize) Error!void { + if (c.d > 256 or heads % c.kv_heads != 0) return error.BadShape; + const sh: c_longlong = @intCast(c.total * c.d); + const ss: c_longlong = @intCast(c.d); + try o.l.tf_causal(f(q), p(c.k), p(c.v), f(out), 1, int(qlen), int(span), int(heads), int(c.kv_heads), int(c.d), scale, int(q_pos0), sh * @as(c_longlong, @intCast(c.kv_heads)), sh, ss, sh * @as(c_longlong, @intCast(c.kv_heads)), sh, ss, c.kind.cache(), null, null, null, o.stream, null); +} + +/// One attention layer of a stream's paged cache: key and value pools (`count` 64-position pages a head), page table. +pub const Paged = struct { k: u64, v: u64, table: u64, kind: Kind, kv_heads: usize, d: usize, count: usize }; + +fn zigLaunches(o: Ops) Error!*const @import("../launches.zig").Launcher { + return o.l; +} + +/// 16-bit `src` values (h * s_head + r * s_row + j elements) of `len` positions from `pos0` into a pool by the table. +pub fn pageWrite(o: Ops, src: u64, pool: u64, table: u64, len: usize, kv_heads: usize, d: usize, s_head: usize, s_row: usize, pos0: usize, count: usize) Error!void { + try (try zigLaunches(o)).pagesWrite(src, pool, table, len, kv_heads, d, s_head, s_row, pos0, count, o.stream); +} + +/// Prefill attention over a stream's pages: the 64-row tile reads pages; other shapes read a flat copy. +pub fn causalPaged(o: Ops, q: u64, c: Paged, out: u64, qlen: usize, span: usize, heads: usize, scale: f32, q_pos0: usize) Error!void { + if (c.d > 256 or heads % c.kv_heads != 0 or c.kind == .f32) return error.BadShape; + const z = try zigLaunches(o); + if (c.d % 64 == 0 and z.wide) return z.pagedCausal(q, c.k, c.v, c.table, out, qlen, span, heads, c.kv_heads, c.d, scale, q_pos0, c.count, c.kind.cache(), o.stream); + const bytes = c.kv_heads * span * c.d * 2; + const flat: Cache = .{ .k = try o.arena.take(bytes), .v = try o.arena.take(bytes), .kind = c.kind, .kv_heads = c.kv_heads, .total = span, .d = c.d }; + try z.pagesGather(c.k, c.table, flat.k, span, c.kv_heads, c.d, c.count, o.stream); + try z.pagesGather(c.v, c.table, flat.v, span, c.kv_heads, c.d, c.count, o.stream); + try causalPrefill(o, q, flat, out, qlen, span, heads, scale, q_pos0); +} + +/// causal_at: `rows` queries (rows, heads, 1, d) fp32 each at its device position over one shared cache. +pub fn causalAt(o: Ops, q: u64, c: Cache, out: u64, rows: usize, heads: usize, scale: f32, pos: u64) Error!void { + if (c.d > 256 or heads % c.kv_heads != 0) return error.BadShape; + const span = c.total; + const scores = try o.arena.of(f32, rows * heads * span); + const stats = try o.arena.of(f32, rows * heads * 2); + const partials = try o.arena.of(f32, rows * heads * ((span + 127) / 128) * c.d); + const sh: c_longlong = @intCast(c.total * c.d); + const ss: c_longlong = @intCast(c.d); + try o.l.tf_causal(f(q), p(c.k), p(c.v), f(out), int(rows), 1, int(span), int(heads), int(c.kv_heads), int(c.d), scale, 0, 0, sh, ss, 0, sh, ss, c.kind.cache(), f(scores), f(stats), f(partials), o.stream, @ptrFromInt(pos)); +} diff --git a/zig/src/hip/ops/draw.zig b/zig/src/hip/ops/draw.zig new file mode 100644 index 00000000000..4d7f5005018 --- /dev/null +++ b/zig/src/hip/ops/draw.zig @@ -0,0 +1,28 @@ +//! The draw inputs read from logits rows: argmax and the top ids. + +const t = @import("types.zig"); +const Ops = @import("ops.zig").Ops; +const Error = t.Error; +const Tensor = t.Tensor; +const p = t.p; +const f = t.f; +const i = t.i; +const int = t.int; + +/// torch.argmax of each of `rows` logits rows (width `n`, fp16 or bf16) into device i32 `out`. +pub fn argmaxRows(o: Ops, logits: Tensor, rows: usize, n: usize, out: u64) Error!void { + if (logits.kind == .f32) return error.BadShape; + try o.l.tf_argmax_rows(p(logits.ptr), @backingInt(logits.kind), int(rows), int(n), i(out), o.stream); +} + +/// softmax(row r)[ids[r]] of `rows` logits rows (fp16 or bf16) into fp32 `out`; of the row's largest when `ids` is 0. +pub fn tokenProb(o: Ops, logits: Tensor, rows: usize, n: usize, ids: u64, out: u64) Error!void { + if (logits.kind == .f32) return error.BadShape; + try o.l.tf_token_prob(p(logits.ptr), @backingInt(logits.kind), int(rows), int(n), if (ids == 0) null else @ptrFromInt(ids), f(out), o.stream); +} + +/// Each row's `ks[r]` largest by (value desc, id asc): ids (i32) and the values' 16-bit patterns, `stride` apart. +pub fn topkRows(o: Ops, logits: Tensor, rows: usize, n: usize, ks: u64, stride: usize, ids: u64, values: u64) Error!void { + if (logits.kind == .f32) return error.BadShape; + try o.l.tf_topk_rows(p(logits.ptr), int(rows), int(n), i(ks), int(stride), i(ids), p(values), o.stream); +} diff --git a/zig/src/hip/ops/elementwise.zig b/zig/src/hip/ops/elementwise.zig new file mode 100644 index 00000000000..a5497c4b8a5 --- /dev/null +++ b/zig/src/hip/ops/elementwise.zig @@ -0,0 +1,26 @@ +//! Casts and the elementwise launches. + +const t = @import("types.zig"); +const Ops = @import("ops.zig").Ops; +const Error = t.Error; +const Tensor = t.Tensor; +const p = t.p; +const int = t.int; + +pub fn cast(o: Ops, src: Tensor, dst: Tensor, n: usize) Error!void { + try o.l.tf_cast(p(src.ptr), @backingInt(src.kind), p(dst.ptr), @backingInt(dst.kind), @intCast(n), o.stream); +} + +pub fn siluMul(o: Ops, gate: Tensor, up: Tensor, out: Tensor, n: usize) Error!void { + if (gate.kind != up.kind or gate.kind != out.kind) return error.BadShape; + try o.l.tf_silu_mul(p(gate.ptr), p(up.ptr), p(out.ptr), @backingInt(out.kind), @intCast(n), o.stream); +} + +pub fn add(o: Ops, x: Tensor, y: Tensor, out: Tensor, n: usize) Error!void { + if (x.kind != y.kind or x.kind != out.kind) return error.BadShape; + try o.l.tf_add(p(x.ptr), p(y.ptr), p(out.ptr), @backingInt(out.kind), @intCast(n), o.stream); +} + +pub fn copyCols(o: Ops, src: Tensor, stride: usize, offset: usize, dst: u64, rows: usize, cols: usize) Error!void { + try o.l.tf_copy_cols(p(src.ptr), @intCast(stride), int(offset), p(dst), @backingInt(src.kind), int(rows), int(cols), o.stream); +} diff --git a/zig/src/hip/ops/moe.zig b/zig/src/hip/ops/moe.zig new file mode 100644 index 00000000000..effaebbe812 --- /dev/null +++ b/zig/src/hip/ops/moe.zig @@ -0,0 +1,42 @@ +//! The mixture-of-experts launches: the router, the pick, the plan, the activation and the combine. + +const t = @import("types.zig"); +const Ops = @import("ops.zig").Ops; +const Error = t.Error; +const Tensor = t.Tensor; +const p = t.p; +const f = t.f; +const i = t.i; +const int = t.int; + +/// MoE combine, residual and next norm in one launch: x = round(x + round(sum_s wts * y)), normed = rms(x) * weight. +pub fn moeTail(o: Ops, x: Tensor, y: u64, wts: u64, weight: u64, normed: Tensor, rows: usize, slots: usize, width: usize, eps: f32) Error!void { + if (x.kind != normed.kind or x.kind == .f32 or slots == 0) return error.BadShape; + const z = o.l; + try z.tf_tail(p(x.ptr), f(y), f(wts), f(weight), p(normed.ptr), @backingInt(x.kind), int(rows), int(slots), int(width), eps, o.stream); +} + +pub fn moeRouter(o: Ops, x: Tensor, rows32: u64, logits: u64, r: usize, d: usize, e: usize) Error!void { + if (o.window) if (o.l.routerWindow(p(x.ptr), @backingInt(x.kind), f(rows32), f(logits), int(r), int(d), int(e), o.stream)) |ran| { + if (ran) return; + } else |err| return err; + if (o.prefill and d % 32 == 0) return o.l.routerTile(p(x.ptr), @backingInt(x.kind), f(rows32), f(logits), int(r), int(d), int(e), o.stream); + try o.l.tf_moe_router(p(x.ptr), @backingInt(x.kind), f(rows32), f(logits), int(r), int(d), int(e), o.stream); +} + +/// The pick rule per row; with `plan` (one row) it also writes the plan's items and members. +pub fn moeSelect(o: Ops, logits: u64, pick: u64, wts: u64, plan: ?struct { items: u64, members: u64 }, capacity: usize, r: usize, experts: usize, top_k: usize) Error!void { + try o.l.tf_moe_select(f(logits), i(pick), f(wts), if (plan) |pl| i(pl.items) else null, if (plan) |pl| i(pl.members) else null, int(capacity), int(r), int(experts), int(top_k), o.stream); +} + +pub fn moeRoute(o: Ops, picks: u64, pairs: usize, experts: usize, tile: usize, members: u64, items: u64, capacity: usize) Error!void { + try o.l.tf_moe_route(@ptrFromInt(picks), int(pairs), int(experts), int(tile), i(members), i(items), int(capacity), o.stream); +} + +pub fn moeAct(o: Ops, both: u64, out: Tensor, pairs: usize, width: usize, limit: f32) Error!void { + try o.l.tf_moe_act(f(both), p(out.ptr), @backingInt(out.kind), int(pairs), int(width), limit, o.stream); +} + +pub fn moeCombine(o: Ops, y: u64, wts: u64, out: Tensor, r: usize, slots: usize, d: usize) Error!void { + try o.l.tf_moe_combine(f(y), f(wts), p(out.ptr), @backingInt(out.kind), int(r), int(slots), int(d), o.stream); +} diff --git a/zig/src/hip/ops/norms.zig b/zig/src/hip/ops/norms.zig new file mode 100644 index 00000000000..5bfb46d2f02 --- /dev/null +++ b/zig/src/hip/ops/norms.zig @@ -0,0 +1,39 @@ +//! Norm launches and the decode tails that fuse a norm. + +const t = @import("types.zig"); +const Ops = @import("ops.zig").Ops; +const Error = t.Error; +const Tensor = t.Tensor; +const p = t.p; +const f = t.f; +const int = t.int; + +pub fn rms(o: Ops, x: Tensor, weight: ?u64, y: Tensor, rows: usize, width: usize, eps: f32) Error!void { + if (x.kind != y.kind or width < 1 or width > 8192) return error.BadShape; + if (rows == 0) return; + try o.l.tf_rms(p(x.ptr), if (weight) |w| f(w) else null, p(y.ptr), @backingInt(x.kind), int(rows), int(width), eps, o.stream); +} + +/// Two sets of fp32 rows (width at most 1024), each normed with its own weight, in one launch. +pub fn rms2(o: Ops, x0: u64, w0: u64, y0: u64, x1: u64, w1: u64, y1: u64, rows: usize, width: usize, eps: f32) Error!void { + const z = o.l; + try z.tf_rms2(f(x0), f(w0), f(y0), f(x1), f(w1), f(y1), int(rows), int(width), eps, o.stream); +} + +/// The linear attention's gated norm: out = rms(y) * weight * round(silu(z)) in z's kind, `width` at most 1024. +pub fn gnormOut(o: Ops, y: u64, weight: u64, z: Tensor, out: Tensor, rows: usize, width: usize, eps: f32) Error!void { + if (z.kind != out.kind or z.kind == .f32) return error.BadShape; + const zig = o.l; + try zig.tf_gnorm_out(f(y), f(weight), p(z.ptr), p(out.ptr), @backingInt(z.kind), int(rows), int(width), eps, o.stream); +} + +/// x = round(x + y) and normed = rms(x) * weight (fp32) in one launch: a residual and the norm after it. +pub fn addRms(o: Ops, x: Tensor, y: Tensor, weight: u64, normed: Tensor, rows: usize, width: usize, eps: f32) Error!void { + if (x.kind != y.kind or x.kind != normed.kind or x.kind == .f32) return error.BadShape; + const z = o.l; + try z.tf_tail(p(x.ptr), p(y.ptr), null, f(weight), p(normed.ptr), @backingInt(x.kind), int(rows), 0, int(width), eps, o.stream); +} + +pub fn gnormSilu(o: Ops, y: u64, z: Tensor, out: Tensor, n: usize) Error!void { + try o.l.tf_gnorm_silu(f(y), p(z.ptr), p(out.ptr), @backingInt(out.kind), @intCast(n), o.stream); +} diff --git a/zig/src/hip/ops/ops.zig b/zig/src/hip/ops/ops.zig new file mode 100644 index 00000000000..b3898b2632d --- /dev/null +++ b/zig/src/hip/ops/ops.zig @@ -0,0 +1,102 @@ +//! Typed launches of the model-free kernels: shapes checked here, as the kernels trust them; `Ops` holds them. + +const std = @import("std"); +const abi = @import("../abi.zig"); +const Launcher = @import("../launches.zig").Launcher; +const Arena = @import("../arena.zig").Arena; +const types = @import("types.zig"); +const products = @import("project.zig"); +const attention = @import("attention.zig"); +const recurrence = @import("recurrence.zig"); +const norms = @import("norms.zig"); +const elementwise = @import("elementwise.zig"); +const moe = @import("moe.zig"); +const draw = @import("draw.zig"); +const tp = @import("tp.zig"); + +pub const Kind = types.Kind; +pub const Error = types.Error; +pub const Tensor = types.Tensor; +pub const Affine = types.Affine; +pub const Projection = @import("core").quant.Projection; + +pub const Ops = struct { + l: *const Launcher, + /// The activations are bf16 (fp16 where the GPU has no bf16 dot2: RDNA2). + bf16: bool, + stream: abi.Stream, + arena: *Arena, + /// A prompt's span: products and router take prefill's kernel, so rows have the same bits however cut. + prefill: bool = false, + /// A lane round's forward: decode tiles at any row count, so a row's bits ignore the rows it shares a round with. + window: bool = false, + + pub const project = products.project; + pub const projectGroup = products.projectGroup; + pub const projectRoutedAct = products.projectRoutedAct; + pub const projectRouted = products.projectRouted; + pub const embedRows = products.embedRows; + pub const affine = products.affine; + pub const affineGroup = products.affineGroup; + pub const affineRoutedAct = products.affineRoutedAct; + pub const affineRouted = products.affineRouted; + pub const embedAffine = products.embedAffine; + pub const denseRows = products.denseRows; + + /// Whether decode.hip's merged launches are on. + pub fn fused(o: Ops) bool { + return o.l.fuse; + } + + pub const attnGate = attention.attnGate; + pub const ropePrefill = attention.ropePrefill; + pub const qkRope = attention.qkRope; + pub const ropeDecode = attention.ropeDecode; + pub const kvWrite = attention.kvWrite; + pub const kvWriteAt = attention.kvWriteAt; + pub const Cache = attention.Cache; + pub const Paged = attention.Paged; + pub const pageWrite = attention.pageWrite; + pub const causalPaged = attention.causalPaged; + pub const causalPrefill = attention.causalPrefill; + pub const causalAt = attention.causalAt; + pub const convPrefill = recurrence.convPrefill; + pub const convDecode = recurrence.convDecode; + pub const convRows = recurrence.convRows; + pub const gdnGatePrefill = recurrence.gdnGatePrefill; + pub const gdnGate = recurrence.gdnGate; + pub const gatedDelta = recurrence.gatedDelta; + pub const rms = norms.rms; + pub const rms2 = norms.rms2; + pub const gnormOut = norms.gnormOut; + pub const addRms = norms.addRms; + pub const gnormSilu = norms.gnormSilu; + pub const cast = elementwise.cast; + pub const siluMul = elementwise.siluMul; + pub const add = elementwise.add; + pub const copyCols = elementwise.copyCols; + pub const moeTail = moe.moeTail; + pub const moeRouter = moe.moeRouter; + pub const moeSelect = moe.moeSelect; + pub const moeRoute = moe.moeRoute; + pub const moeAct = moe.moeAct; + pub const moeCombine = moe.moeCombine; + pub const argmaxRows = draw.argmaxRows; + pub const topkRows = draw.topkRows; + pub const tokenProb = draw.tokenProb; + pub const addWide = tp.addWide; + pub const moeLocalize = tp.moeLocalize; + pub const moeForeignItems = tp.moeForeignItems; + pub const moeZeroForeign = tp.moeZeroForeign; +}; + +test "dtype numberings of the three kernel families" { + try std.testing.expectEqual(@as(c_int, 1), @backingInt(Kind.f16)); + try std.testing.expectEqual(@as(c_int, 0), Kind.f16.cache()); + try std.testing.expectEqual(@as(c_int, 2), Kind.f16.table()); + try std.testing.expectEqual(@as(c_int, 1), Kind.bf16.table()); +} + +test "every launch compiles" { + std.testing.refAllDecls(Ops); +} diff --git a/zig/src/hip/ops/plan.zig b/zig/src/hip/ops/plan.zig new file mode 100644 index 00000000000..16b3d9d03b9 --- /dev/null +++ b/zig/src/hip/ops/plan.zig @@ -0,0 +1,100 @@ +//! A lane round's launches over its device plan: arguments depend only on the plan's shape and the layer. + +const t = @import("types.zig"); +const launches = @import("../launches.zig"); +const Ops = @import("ops.zig").Ops; + +const Tensor = t.Tensor; +const Error = t.Error; + +pub const Args = launches.PlanArgs; +pub const Plan = launches.PlanRef; +pub const Keep = launches.PlanKeep; + +fn launcher(o: Ops) Error!*const launches.Launcher { + return o.l; +} + +fn int(n: usize) c_int { + return @intCast(n); +} + +/// The conv's norm weights of q and k heads (heads of 128) and the delta rule's gate and beta computed beside it. +pub const Norm = struct { q: u64, k: u64, eps: f32 }; +pub const Gates = struct { a: Tensor, b: Tensor, a_log: u64, dt_bias: u64, gate: u64, beta: u64, count: usize, heads: usize }; + +/// The round's rows through the linear attention's conv from each slot's window, split into q, k, v fp32. +pub fn convSplit(o: Ops, x: Tensor, weight: u64, qn: u64, kn: u64, v: u64, p: Plan, layer: usize, channels: usize, kernel: usize, kw: usize, vw: usize, norm: ?Norm, gates: ?Gates) Error!void { + if (kernel < 1 or kernel > 8 or x.kind == .f32) return error.BadShape; + const z = try launcher(o); + var c: launches.ConvArgs = .{ + .x = x.ptr, + .kind = @backingInt(x.kind), + .weight = weight, + .state = 0, + .qn = qn, + .kn = kn, + .v = v, + .channels = int(channels), + .kernel = int(kernel), + .rows = int(p.rows), + .kw = int(kw), + .vw = int(vw), + .plan = p.args, + .layer = int(layer), + .slots = int(p.slots), + }; + if (norm) |nm| { + c.qw = nm.q; + c.kw_w = nm.k; + c.eps = nm.eps; + c.norm = 128; + } + if (gates) |g| { + if (g.a.kind != x.kind or g.b.kind != x.kind) return error.BadShape; + c.ga = g.a.ptr; + c.gb = g.b.ptr; + c.a_log = g.a_log; + c.dt_bias = g.dt_bias; + c.gate = g.gate; + c.beta = g.beta; + c.gcount = int(g.count); + c.heads = int(g.heads); + } + try z.tf_conv_split(c, o.stream); +} + +/// The DeltaNet recurrence of every slot's rows: q, k (rows, Hk, dk), v, y (rows, Hv, dv), gate, beta (rows, Hv) fp32. +pub fn gatedDelta(o: Ops, q: u64, k: u64, v: u64, gate: u64, beta: u64, y: u64, p: Plan, layer: usize, key_heads: usize, value_heads: usize, dk: usize, dv: usize) Error!void { + try (try launcher(o)).planGatedDelta(q, k, v, gate, beta, y, p, layer, key_heads, value_heads, dk, dv, o.stream); +} + +/// Each row's keys (fp32, rotated) and values (the activation kind) into its slot's caches at its position. +pub fn kvWrite(o: Ops, keys: u64, values: Tensor, p: Plan, layer: usize, kv_heads: usize, d: usize) Error!void { + if (values.kind == .f32) return error.BadShape; + try (try launcher(o)).planKvWrite(keys, values.ptr, @backingInt(values.kind), p, layer, kv_heads, d, o.stream); +} + +/// One query a row (rows, heads, d) fp32 over its slot's caches up to its position, the walk over `span` keys. +pub fn causal(o: Ops, q: u64, kind: t.Kind, out: u64, p: Plan, layer: usize, heads: usize, kv_heads: usize, d: usize, span: usize, scale: f32) Error!void { + const tiles = (span + 127) / 128; + const scores = try o.arena.of(f32, p.rows * heads * span); + const stats = try o.arena.of(f32, p.rows * heads * 2); + const partials = try o.arena.of(f32, p.rows * heads * tiles * d); + try (try launcher(o)).planCausal(q, out, scores, stats, partials, p, layer, heads, kv_heads, d, span, scale, @backingInt(kind), o.stream); +} + +/// Keeps the listed slots' rows (see `launches.PlanKeep`). +pub fn keep(o: Ops, p: Plan, k: Keep) Error!void { + try (try launcher(o)).planKeep(p, k, o.stream); +} + +/// The kept slots' DeltaNet states replayed through their kept rows (see `launches.planGdnReplay`). +pub fn gdnReplay(o: Ops, keep_counts: u64, p: Plan, key_heads: usize, value_heads: usize, dk: usize, dv: usize, layers: usize) Error!void { + try (try launcher(o)).planGdnReplay(keep_counts, p, key_heads, value_heads, dk, dv, layers, o.stream); +} + +/// Row r of `dst` (`words` words each) from the address in `srcs[r]` (device u64s), for `rows` rows. +pub fn gather(o: Ops, srcs: u64, dst: u64, words: usize, rows: usize) Error!void { + try (try launcher(o)).planGather(srcs, dst, words, rows, o.stream); +} diff --git a/zig/src/hip/ops/project.zig b/zig/src/hip/ops/project.zig new file mode 100644 index 00000000000..9ef2038841b --- /dev/null +++ b/zig/src/hip/ops/project.zig @@ -0,0 +1,223 @@ +//! The products on a projection of any format, dispatched on its tag; `affine*` are the MLX affine path behind them. + +const t = @import("types.zig"); +const quant = @import("core").quant; +const launches = @import("../launches.zig"); +const affine_launch = @import("../launches/affine.zig"); +const registry = @import("core").registry; +const Ops = @import("ops.zig").Ops; +const Error = t.Error; +const Tensor = t.Tensor; +const Affine = t.Affine; +const Projection = quant.Projection; +const mlx = quant.mlx; +const p = t.p; +const f = t.f; +const i = t.i; +const int = t.int; + +/// The MLX matrix of a projection as the MLX launches take it. +fn affineOf(proj: Projection, h: mlx.Matrix) Affine { + const tables: t.Kind = switch (h.tables) { + .f32 => .f32, + .bf16 => .bf16, + .f16 => .f16, + }; + return .{ .words = h.words, .scale = h.scale, .bias = h.bias, .tables = tables, .n = proj.n, .k = proj.k, .bits = h.bits, .group = h.group, .partial = proj.partial }; +} + +/// matmul(x, proj) for a projection of any format: fp32 when `f32_out`, else x's kind (the MLX rules of `affine`). +pub fn project(o: Ops, x: Tensor, proj: Projection, m: usize, f32_out: bool) Error!Tensor { + switch (proj.handle) { + .mlx => |h| return affine(o, x, affineOf(proj, h), m, f32_out), + .dense => |h| { + if (f32_out or m == 0 or x.kind == .f32) return error.BadShape; + const out: Tensor = .{ .ptr = try o.arena.take(m * proj.n * x.kind.size()), .kind = x.kind }; + try denseRows(o, x, h.weight, out, m, proj.n, proj.k); + return out; + }, + } +} + +/// Up to four products of the same `m` rows in one launch; false, nothing launched, when no grouped tile takes them. +pub fn projectGroup(o: Ops, x: Tensor, ps: []const Projection, m: usize, outs: []Tensor) Error!bool { + var ws: [4]Affine = undefined; + if (ps.len > ws.len) return false; + for (ps, ws[0..ps.len]) |pr, *w| switch (pr.handle) { + .mlx => |h| w.* = affineOf(pr, h), + .dense => return false, + }; + return affineGroup(o, x, ws[0..ps.len], m, outs); +} + +/// The routed gate and up with the activation as the epilogue; null when the format or the tile does not take it. +pub fn projectRoutedAct(o: Ops, x: Tensor, proj: Projection, items: u64, count: usize, members: u64, pairs: usize, x_div: usize, rows: usize, limit: f32) Error!?Tensor { + switch (proj.handle) { + .mlx => |h| return affineRoutedAct(o, x, affineOf(proj, h), items, count, members, pairs, x_div, rows, limit), + .dense => return null, + } +} + +/// matmul_routed on a stack of experts: every item in one launch; out (pairs, N) fp32. +pub fn projectRouted(o: Ops, x: Tensor, proj: Projection, items: u64, count: usize, members: u64, pairs: usize, x_div: usize, rows: usize) Error!u64 { + switch (proj.handle) { + .mlx => |h| return affineRouted(o, x, affineOf(proj, h), items, count, members, pairs, x_div, rows), + .dense => return error.BadShape, + } +} + +/// gather_rows: `n` embedding rows of a table of any format with a row gather, by device ids, dequantized into `out`. +pub fn embedRows(o: Ops, table: Projection, ids: u64, n: usize, out: Tensor) Error!void { + switch (table.handle) { + .mlx => |h| return embedAffine(o, affineOf(table, h), ids, n, out), + .dense => |h| try o.l.tf_embed_dense(f(h.weight), @ptrFromInt(ids), int(n), int(table.k), p(out.ptr), @backingInt(out.kind), o.stream), + } +} + +/// The product of `m` rows of x with `w` as the registry sees it; a lane round keeps its decode tile at any row count. +fn shapeOf(o: Ops, x: Tensor, w: Affine, m: usize) registry.Shape { + return .{ + .m = @intCast(m), + .n = w.n, + .k = w.k, + .bits = w.bits, + .group = w.group, + .fp16 = x.kind == .f16, + .tables = switch (w.tables) { + .f32 => .f32, + .bf16 => .bf16, + .f16 => .f16, + }, + .x_aligned = x.ptr % 16 == 0, + .words_aligned = w.words % affine_launch.Kernels.gemmAlign(w.bits) == 0, + .round = o.window, + }; +} + +/// matmul(x, ...) as the Python wrapper runs it on the auto schedule: fp32 (`f32_out`), else the input dtype. +pub fn affine(o: Ops, x: Tensor, w: Affine, m: usize, f32_out: bool) Error!Tensor { + try w.check(); + if (m == 0) return error.BadShape; + const fp16 = x.kind == .f16; + if (x.kind == .f32 or (fp16 and o.bf16) or (!fp16 and !o.bf16)) return error.BadShape; + const n: usize = w.n; + const kind = w.tables.table(); + var half = false; + const z = o.l; + const shape = shapeOf(o, x, w, m); + const tile = z.affine.choose(.project, if (o.prefill) .prefill else .decode, shape) orelse return error.BadShape; + half = !f32_out and !o.prefill and tile.roundsAct(shape); + const out = try o.arena.take(m * n * @as(usize, if (half) 2 else 4)); + { + const arg: affine_launch.Arg = .{ + .x = x.ptr, + .words = w.words, + .scale = .{ .p = w.scale, .kind = kind }, + .bias = .{ .p = w.bias, .kind = kind }, + .out = if (half) 0 else out, + .m = int(m), + .n = int(n), + .k = int(w.k), + .bits = w.bits, + .group = w.group, + .fp16 = @intFromBool(fp16), + .out16 = if (half) out else 0, + }; + try tile.launch(&z.affine, .{ .r = z.r, .s = o.stream, .arg = arg }); + } + if (half) return .{ .ptr = out, .kind = x.kind }; + if (f32_out) return .{ .ptr = out, .kind = .f32 }; + const narrow = try o.arena.take(m * n * 2); + try o.cast(.{ .ptr = out, .kind = .f32 }, .{ .ptr = narrow, .kind = x.kind }, m * n); + return .{ .ptr = narrow, .kind = x.kind }; +} + +/// Up to four products of the same rows in one stream-tile launch, rounded to x's kind; false if unsupported. +pub fn affineGroup(o: Ops, x: Tensor, ws: []const Affine, m: usize, outs: []Tensor) Error!bool { + const z = o.l; + if (o.prefill or !o.fused() or ws.len < 2 or ws.len > 4 or m == 0 or x.kind == .f32) return false; + var widest: u32 = 0; + for (ws) |w| { + try w.check(); + if (w.k != ws[0].k or w.bits != ws[0].bits or w.group != ws[0].group or w.tables != ws[0].tables or w.partial) return false; + widest = @max(widest, w.n); + } + const kind = ws[0].tables.table(); + var widest_w = ws[0]; + widest_w.n = widest; + if (z.affine.choose(.group, .decode, shapeOf(o, x, widest_w, m)) == null) return false; + var sides: [4]affine_launch.Side = undefined; + for (ws, outs[0..ws.len], sides[0..ws.len]) |w, *out, *side| { + out.* = .{ .ptr = try o.arena.take(m * w.n * 2), .kind = x.kind }; + side.* = .{ .words = w.words, .scale = w.scale, .bias = w.bias, .n = int(w.n), .out = out.ptr }; + } + const arg: affine_launch.Arg = .{ + .x = x.ptr, + .words = 0, + .scale = .{ .p = 0, .kind = kind }, + .bias = .{ .p = 0, .kind = kind }, + .out = 0, + .m = int(m), + .n = int(widest), + .k = int(ws[0].k), + .bits = int(ws[0].bits), + .group = int(ws[0].group), + .fp16 = @intFromBool(x.kind == .f16), + }; + try z.affine.groupRun(z.r, arg, sides[0..ws.len], true, o.stream); + return true; +} + +/// Routed gate and up in one launch, silu(gate) * up as epilogue into x's kind; null when the tile cannot. +pub fn affineRoutedAct(o: Ops, x: Tensor, w: Affine, items: u64, count: usize, members: u64, pairs: usize, x_div: usize, rows: usize, limit: f32) Error!?Tensor { + const z = o.l; + if (o.prefill or !o.fused() or x.kind == .f32 or w.n % 2 != 0) return null; + try w.check(); + const kind = w.tables.table(); + var shape = shapeOf(o, x, w, rows); + shape.pairs = true; + if (z.affine.choose(.routed_act, .decode, shape) == null) return null; + const out = try o.arena.take(pairs * (w.n / 2) * 2); + const arg: affine_launch.Arg = .{ + .x = x.ptr, + .words = w.words, + .scale = .{ .p = w.scale, .kind = kind }, + .bias = .{ .p = w.bias, .kind = kind }, + .out = 0, + .m = int(rows), + .n = int(w.n), + .k = int(w.k), + .bits = int(w.bits), + .group = int(w.group), + .fp16 = @intFromBool(x.kind == .f16), + .route = .{ .items = items, .members = members, .x_div = int(x_div) }, + .out16 = out, + }; + if (!try z.affine.pairRun(z.r, arg, limit, int(count), o.stream)) return null; + return .{ .ptr = out, .kind = x.kind }; +} + +/// matmul_routed: every item (expert, first, count) in one launch over stacked weights; out (pairs, N) fp32. +pub fn affineRouted(o: Ops, x: Tensor, w: Affine, items: u64, count: usize, members: u64, pairs: usize, x_div: usize, rows: usize) Error!u64 { + try w.check(); + const out = try o.arena.of(f32, pairs * w.n); + if (o.prefill) { + const z = o.l; + const kind = w.tables.table(); + try z.affine.prefillLaunch(z.r, .{ .x = x.ptr, .words = w.words, .scale = .{ .p = w.scale, .kind = kind }, .bias = .{ .p = w.bias, .kind = kind }, .out = out, .m = int(rows), .n = int(w.n), .k = int(w.k), .bits = int(w.bits), .group = int(w.group), .fp16 = @intFromBool(x.kind == .f16), .route = .{ .items = items, .members = members, .x_div = int(x_div) } }, o.stream, int(count)); + return out; + } + try o.l.tf_affine_routed(p(x.ptr), p(w.words), p(w.scale), p(w.bias), w.tables.table(), p(out), i(items), int(count), i(members), int(x_div), int(rows), int(w.n), int(w.k), w.bits, w.group, @intFromBool(x.kind == .f16), o.stream); + return out; +} + +/// The MLX affine gather: `n` embedding rows of width `table.k` by device ids, dequantized into `out`. +pub fn embedAffine(o: Ops, table: Affine, ids: u64, n: usize, out: Tensor) Error!void { + try table.check(); + try o.l.tf_embed_rows(p(table.words), p(table.scale), p(table.bias), @backingInt(table.tables), @ptrFromInt(ids), int(n), table.bits, table.group, int(table.k), p(out.ptr), @backingInt(out.kind), o.stream); +} + +/// x (rows, k) of x's kind times fp32 weights (n, k), out (rows, n) in x's kind: an unquantized draft projection. +pub fn denseRows(o: Ops, x: Tensor, w: u64, out: Tensor, rows: usize, n: usize, k: usize) Error!void { + try o.l.tf_dense_rows(p(x.ptr), @backingInt(x.kind), f(w), p(out.ptr), int(rows), int(n), int(k), o.stream); +} diff --git a/zig/src/hip/ops/recurrence.zig b/zig/src/hip/ops/recurrence.zig new file mode 100644 index 00000000000..cf2b5f8be57 --- /dev/null +++ b/zig/src/hip/ops/recurrence.zig @@ -0,0 +1,36 @@ +//! The linear attention: the conv, the gates and the DeltaNet recurrence. + +const t = @import("types.zig"); +const Ops = @import("ops.zig").Ops; +const Error = t.Error; +const Tensor = t.Tensor; +const p = t.p; +const f = t.f; +const int = t.int; + +pub fn convPrefill(o: Ops, x: Tensor, weight: u64, state: ?u64, out: u64, new_state: u64, len: usize, channels: usize, kernel: usize) Error!void { + if (kernel < 1 or kernel > 8) return error.BadShape; + try o.l.tf_conv_prefill(p(x.ptr), @backingInt(x.kind), f(weight), if (state) |s| f(s) else null, f(out), f(new_state), int(len), int(channels), int(kernel), o.stream); +} + +pub fn convDecode(o: Ops, x: u64, weight: u64, state: u64, y: u64, channels: usize, kernel: usize) Error!void { + try o.l.tf_conv_decode(f(x), f(weight), f(state), f(y), 1, int(channels), int(kernel), o.stream); +} + +pub fn convRows(o: Ops, x: u64, weight: u64, state: u64, y: u64, states: ?u64, rows: usize, channels: usize, kernel: usize) Error!void { + try o.l.tf_conv_rows(f(x), f(weight), f(state), f(y), if (states) |s| f(s) else null, int(rows), int(channels), int(kernel), o.stream); +} + +pub fn gdnGatePrefill(o: Ops, a: Tensor, b: Tensor, a_log: u64, dt_bias: u64, gate: u64, beta: u64, count: usize, heads: usize) Error!void { + try o.l.tf_gdn_gate_prefill(p(a.ptr), p(b.ptr), @backingInt(a.kind), f(a_log), f(dt_bias), f(gate), f(beta), int(count), int(heads), o.stream); +} + +/// The fused gate over `elements` values of a and b (rows times heads). +pub fn gdnGate(o: Ops, a: Tensor, b: Tensor, a_log: u64, dt_bias: u64, gate: u64, beta: u64, elements: usize, heads: usize) Error!void { + try o.l.tf_gdn_gate(p(a.ptr), p(b.ptr), @backingInt(a.kind), f(a_log), f(dt_bias), f(gate), f(beta), int(elements), int(heads), o.stream); +} + +/// The DeltaNet recurrence in fp32, state in place, the same walk at every length. +pub fn gatedDelta(o: Ops, q: u64, k: u64, v: u64, gate: u64, beta: u64, state: u64, y: u64, length: usize, key_heads: usize, value_heads: usize, dk: usize, dv: usize, states: ?u64) Error!void { + try o.l.tf_gated_delta(f(q), f(k), f(v), f(gate), f(beta), f(state), f(y), 1, int(length), int(key_heads), int(value_heads), int(dk), int(dv), o.stream, if (states) |s| f(s) else null); +} diff --git a/zig/src/hip/ops/tp.zig b/zig/src/hip/ops/tp.zig new file mode 100644 index 00000000000..d3cb31fcf10 --- /dev/null +++ b/zig/src/hip/ops/tp.zig @@ -0,0 +1,31 @@ +//! The launches a tensor-parallel rank adds: the fp32 sum into a residual and the local expert ids. + +const t = @import("types.zig"); +const Ops = @import("ops.zig").Ops; +const Error = t.Error; +const Tensor = t.Tensor; +const p = t.p; +const f = t.f; +const i = t.i; +const int = t.int; + +/// out = round(x + y): an activation `x` plus an fp32 sum `y`, rounded once to x's kind (a tp residual). +pub fn addWide(o: Ops, x: Tensor, y: u64, out: Tensor, n: usize) Error!void { + if (x.kind == .f32 or x.kind != out.kind) return error.BadShape; + try o.l.tf_add_wide(p(x.ptr), f(y), p(out.ptr), @backingInt(out.kind), @intCast(n), o.stream); +} + +/// out[i] = remap[pick[i]], or `skip` where it is negative: a tp rank's local expert ids. +pub fn moeLocalize(o: Ops, pick: u64, remap: u64, out: u64, n: usize, skip: usize) Error!void { + try o.l.tf_moe_localize(i(pick), i(remap), i(out), int(n), int(skip), o.stream); +} + +/// Zeroes the pair count of every plan item of the `skip` expert. +pub fn moeForeignItems(o: Ops, items: u64, count: usize, skip: usize) Error!void { + try o.l.tf_moe_foreign_items(i(items), int(count), int(skip), o.stream); +} + +/// Zeroes the rows of `y` (pairs, d) fp32 whose pick is `skip`. +pub fn moeZeroForeign(o: Ops, y: u64, picks: u64, skip: usize, pairs: usize, d: usize) Error!void { + try o.l.tf_moe_zero_foreign(f(y), i(picks), int(skip), @intCast(pairs), int(d), o.stream); +} diff --git a/zig/src/hip/ops/types.zig b/zig/src/hip/ops/types.zig new file mode 100644 index 00000000000..50cb8cc8bbc --- /dev/null +++ b/zig/src/hip/ops/types.zig @@ -0,0 +1,76 @@ +//! The types the launches share: buffer kinds, a device tensor, an MLX affine matrix and the address casts. + +const runtime = @import("../runtime.zig"); + +/// act.hpp's numbering: the activation and fp32 buffers the torch-op kernels read and write. +pub const Kind = enum(c_int) { + f32 = 0, + f16 = 1, + bf16 = 2, + + pub fn size(k: Kind) usize { + return if (k == .f32) 4 else 2; + } + + /// The attention kernel's cache numbering: 0 fp16, 1 bf16, 2 fp32. + pub fn cache(k: Kind) c_int { + return switch (k) { + .f16 => 0, + .bf16 => 1, + .f32 => 2, + }; + } + + /// The affine kernels' table numbering: 0 fp32, 1 bf16, 2 fp16. + pub fn table(k: Kind) c_int { + return switch (k) { + .f32 => 0, + .bf16 => 1, + .f16 => 2, + }; + } +}; + +pub const Error = runtime.Error || error{ OutOfDeviceMemory, BadShape }; + +/// A device buffer of `kind` values. +pub const Tensor = struct { ptr: u64, kind: Kind }; + +/// One MLX affine matrix (N, K): packed words (N, K * bits / 32), scale and bias (N, K / group) of `tables`. +pub const Affine = struct { + words: u64, + scale: u64, + bias: u64, + tables: Kind, + n: u32, + k: u32, + bits: u8, + group: u16, + /// A tensor-parallel slice along K: the product stays fp32, one rank's share of a sum. + partial: bool = false, + + pub fn check(a: Affine) Error!void { + const ok_bits = switch (a.bits) { + 2, 3, 4, 5, 6, 8 => true, + else => false, + }; + if (!ok_bits or (a.group != 32 and a.group != 64 and a.group != 128)) return error.BadShape; + if (a.k % a.group != 0 or (@as(u64, a.k) * a.bits) % 32 != 0) return error.BadShape; + } +}; + +pub fn p(addr: u64) ?*anyopaque { + return @ptrFromInt(addr); +} + +pub fn f(addr: u64) ?[*]f32 { + return @ptrFromInt(addr); +} + +pub fn i(addr: u64) ?[*]i32 { + return @ptrFromInt(addr); +} + +pub fn int(v: anytype) c_int { + return @intCast(v); +} diff --git a/zig/src/hip/policy.zig b/zig/src/hip/policy.zig new file mode 100644 index 00000000000..38d76560516 --- /dev/null +++ b/zig/src/hip/policy.zig @@ -0,0 +1,231 @@ +//! What a run may use, resolved once at open; nothing below the engine reads the environment, it reads this. + +const std = @import("std"); +const Launcher = @import("launches.zig").Launcher; +const affine = @import("launches/affine.zig"); + +pub const Choice = enum { auto, on, off }; +/// The prefill attention tile: `f32` keeps the one-row kernel. +pub const Attention = enum { auto, f32 }; +/// One kernel family switched to its reference, apart from `kernels=reference` that switches them all. +pub const Pick = enum { auto, reference }; + +/// MTP drafting: `--mtp-drafts` and `--mtp-confidence`. +pub const Mtp = struct { drafts: u8 = 3, confidence: f64 = 0.3 }; + +pub const Policy = struct { + matrix: Choice = .auto, + attention: Attention = .auto, + kernels: Pick = .auto, + graphs: Choice = .auto, + /// Reference kernels one at a time: decode stream tile, prefill GEMM tile, fused decode tails. + stream: Pick = .auto, + gemm: Pick = .auto, + fuse: Pick = .auto, + prefill_step: u32 = 1024, + /// Prompt rows a chunk while other streams decode: a multiple of 64 dividing 1024 (the idle chunk). + fill_rows: u32 = 512, + /// Set from the serve flags, not keys: rank 0's travel to the other ranks. + mtp: Mtp = .{}, + /// Snapshots the radix prompt cache keeps (`--checkpoint-slots`). + slots: u32 = 8, + /// Rank whose graph capture fails on purpose, for the tests of the fallback (-1: none). Local to a rank. + graph_fail: i32 = -1, + + pub const Error = error{ UnknownKey, BadValue, StepNotAligned }; + + /// Whether the decode stream tile is on. + pub fn streamOn(p: *const Policy) bool { + return p.kernels != .reference and p.stream != .reference; + } + + /// Whether the prefill GEMM tile (not the reference block tile) takes the products. + pub fn gemmOn(p: *const Policy) bool { + return p.kernels != .reference and p.gemm != .reference; + } + + /// Whether decode.hip's merged launches are on. + pub fn fused(p: *const Policy) bool { + return p.kernels != .reference and p.fuse != .reference; + } + + /// What the kernel launches choose under this policy. + pub fn choices(p: *const Policy) Launcher.Choices { + const matrix: affine.Matrix = switch (p.matrix) { + .auto => .auto, + .on => .on, + .off => .off, + }; + return .{ .fuse = p.fused(), .wide = p.wideAttention(), .products = .{ .matrix = matrix, .stream = p.streamOn(), .gemm = p.gemmOn() } }; + } + + /// Whether the 64-row prefill attention tile is on. + pub fn wideAttention(p: *const Policy) bool { + return p.attention != .f32; + } + + /// Whether rounds replay captured graphs on a group of `world` ranks. + pub fn graphsOn(p: *const Policy, world: usize) bool { + return switch (p.graphs) { + .on => true, + .off => false, + .auto => world == 1, + }; + } + + /// Applies `key=value,key=value` (`--policy`'s and TF_POLICY's syntax) over this policy, all of it or none. + pub fn apply(p: *Policy, text: []const u8) Error!void { + var next = p.*; + var it = std.mem.tokenizeAny(u8, text, ", "); + while (it.next()) |pair| { + const eq = std.mem.indexOfScalar(u8, pair, '=') orelse return error.BadValue; + try next.set(pair[0..eq], pair[eq + 1 ..]); + } + if (next.prefill_step == 0 or next.prefill_step % 64 != 0) return error.StepNotAligned; + if (next.fill_rows == 0 or next.fill_rows % 64 != 0 or 1024 % next.fill_rows != 0) return error.StepNotAligned; + p.* = next; + } + + fn set(p: *Policy, key: []const u8, value: []const u8) Error!void { + const eql = std.mem.eql; + if (eql(u8, key, "matrix")) p.matrix = try parseEnum(Choice, value) else if (eql(u8, key, "attention")) p.attention = try parseEnum(Attention, value) else if (eql(u8, key, "kernels")) p.kernels = try parseEnum(Pick, value) else if (eql(u8, key, "graphs")) p.graphs = try parseEnum(Choice, value) else if (eql(u8, key, "stream")) p.stream = try parseEnum(Pick, value) else if (eql(u8, key, "gemm")) p.gemm = try parseEnum(Pick, value) else if (eql(u8, key, "fuse")) p.fuse = try parseEnum(Pick, value) else if (eql(u8, key, "prefill_step")) { + p.prefill_step = std.fmt.parseInt(u32, value, 10) catch return error.BadValue; + } else if (eql(u8, key, "fill_rows")) { + p.fill_rows = std.fmt.parseInt(u32, value, 10) catch return error.BadValue; + } else if (eql(u8, key, "graph_fail")) { + p.graph_fail = std.fmt.parseInt(i32, value, 10) catch return error.BadValue; + } else return error.UnknownKey; + } + + fn parseEnum(comptime E: type, value: []const u8) Error!E { + return std.meta.stringToEnum(E, value) orelse error.BadValue; + } + + /// One line for the start-up log and server info; default and local fields are left out of the keys. + pub fn format(p: Policy, w: *std.Io.Writer) std.Io.Writer.Error!void { + try w.print("matrix={t},attention={t},kernels={t},graphs={t},prefill_step={d},fill_rows={d}", .{ p.matrix, p.attention, p.kernels, p.graphs, p.prefill_step, p.fill_rows }); + if (p.stream != .auto) try w.print(",stream={t}", .{p.stream}); + if (p.gemm != .auto) try w.print(",gemm={t}", .{p.gemm}); + if (p.fuse != .auto) try w.print(",fuse={t}", .{p.fuse}); + if (p.graph_fail >= 0) try w.print(",graph_fail={d}", .{p.graph_fail}); + try w.print("; mtp drafts {d} under {d}, {d} snapshots", .{ p.mtp.drafts, p.mtp.confidence, p.slots }); + } + + pub const word_count = 7; + + /// The policy as a fixed set of words, for rank 0 to send and every rank to use the same. + pub fn words(p: Policy) [word_count]u32 { + const conf: u64 = @bitCast(p.mtp.confidence); + const pack = [_]u32{ + @backingInt(p.matrix), @backingInt(p.attention), @backingInt(p.kernels), @backingInt(p.graphs), + @backingInt(p.stream), @backingInt(p.gemm), @backingInt(p.fuse), + }; + var nibbles: [2]u32 = .{ 0, 0 }; + for (pack, 0..) |v, i| nibbles[i / 8] |= v << @intCast(4 * (i % 8)); + return .{ nibbles[0], nibbles[1] | @as(u32, p.mtp.drafts) << 24, p.prefill_step, @truncate(conf), @intCast(conf >> 32), p.slots, p.fill_rows }; + } + + /// `local` with every field rank 0 sent; a rank keeps its own graph fault. + pub fn fromWords(w: [word_count]u32, local: Policy) Policy { + var p = local; + var vals: [7]u32 = undefined; + for (&vals, 0..) |*v, i| v.* = (w[i / 8] >> @intCast(4 * (i % 8))) & 0xf; + p.matrix = @fromBackingInt(@intCast(vals[0])); + p.attention = @fromBackingInt(@intCast(vals[1])); + p.kernels = @fromBackingInt(@intCast(vals[2])); + p.graphs = @fromBackingInt(@intCast(vals[3])); + p.stream = @fromBackingInt(@intCast(vals[4])); + p.gemm = @fromBackingInt(@intCast(vals[5])); + p.fuse = @fromBackingInt(@intCast(vals[6])); + p.mtp = .{ .drafts = @truncate(w[1] >> 24), .confidence = @bitCast(@as(u64, w[3]) | @as(u64, w[4]) << 32) }; + p.prefill_step = w[2]; + p.slots = w[5]; + p.fill_rows = w[6]; + return p; + } + + /// Where TF_POLICY is read from, once, at resolution. + pub const Env = struct { + /// Read the process's variables after `vars`. + process: bool = false, + vars: []const [2][]const u8 = &.{}, + + pub const none: Env = .{}; + pub const current: Env = .{ .process = true }; + + fn get(e: Env, name: [:0]const u8) ?[]const u8 { + for (e.vars) |v| if (std.mem.eql(u8, v[0], name)) return v[1]; + if (!e.process) return null; + return std.mem.span(std.c.getenv(name.ptr) orelse return null); + } + }; + + /// What resolution found besides the flags (TF_POLICY), for the start-up line. + pub const Notes = struct { + buf: [768]u8 = undefined, + len: usize = 0, + + fn add(n: *Notes, comptime fmt: []const u8, args: anytype) void { + const out = std.fmt.bufPrint(n.buf[n.len..], fmt, args) catch return; + n.len += out.len; + } + + pub fn text(n: *const Notes) []const u8 { + return n.buf[0..n.len]; + } + }; + + /// The policy: defaults, then `flags` (`--policy`), then TF_POLICY; `notes` says when TF_POLICY acted. + pub fn resolve(flags: []const u8, env: Env, notes: *Notes) Error!Policy { + var p: Policy = .{}; + try p.apply(flags); + if (env.get("TF_POLICY")) |text| { + notes.add("TF_POLICY={s}; ", .{text}); + try p.apply(text); + } + return p; + } +}; + +test "apply sets fields and refuses what it does not know" { + var p: Policy = .{}; + try p.apply("matrix=off, kernels=reference,prefill_step=2048"); + try std.testing.expectEqual(Choice.off, p.matrix); + try std.testing.expectEqual(Pick.reference, p.kernels); + try std.testing.expectEqual(@as(u32, 2048), p.prefill_step); + try std.testing.expectError(error.UnknownKey, p.apply("wmma=on")); + try std.testing.expectError(error.UnknownKey, p.apply("mtp_drafts=2")); + try std.testing.expectError(error.BadValue, p.apply("matrix=maybe")); + try std.testing.expectError(error.StepNotAligned, p.apply("prefill_step=1000")); + try p.apply("fill_rows=256"); + try std.testing.expectEqual(@as(u32, 256), p.fill_rows); + for ([_][]const u8{ "fill_rows=0", "fill_rows=100", "fill_rows=384", "fill_rows=2048" }) |bad| try std.testing.expectError(error.StepNotAligned, p.apply(bad)); + try std.testing.expectEqual(@as(u32, 256), p.fill_rows); +} + +test "a policy survives its words" { + var p: Policy = .{ .mtp = .{ .drafts = 2, .confidence = 0.25 }, .slots = 4, .graph_fail = 1 }; + try p.apply("matrix=on,attention=f32,graphs=off,fuse=reference,fill_rows=128"); + const back = Policy.fromWords(p.words(), .{ .graph_fail = 1 }); + try std.testing.expectEqualDeep(p, back); +} + +test "TF_POLICY speaks after the flags, and the reference switches" { + var notes: Policy.Notes = .{}; + const env: Policy.Env = .{ .vars = &.{.{ "TF_POLICY", "matrix=on,stream=reference,attention=f32,graphs=off" }} }; + const p = try Policy.resolve("matrix=off", env, ¬es); + try std.testing.expectEqual(Choice.on, p.matrix); + try std.testing.expect(!p.streamOn() and p.gemmOn() and p.fused() and !p.wideAttention()); + try std.testing.expect(!p.graphsOn(1) and !p.graphsOn(2)); + try std.testing.expect(std.mem.indexOf(u8, notes.text(), "TF_POLICY=") != null); + var reference: Policy = .{}; + try reference.apply("kernels=reference"); + try std.testing.expect(!reference.streamOn() and !reference.gemmOn() and !reference.fused()); +} + +test "graphs follow the group unless the policy says" { + var p: Policy = .{}; + try std.testing.expect(p.graphsOn(1) and !p.graphsOn(2)); + try p.apply("graphs=on"); + try std.testing.expect(p.graphsOn(2)); +} diff --git a/zig/src/hip/raw.zig b/zig/src/hip/raw.zig new file mode 100644 index 00000000000..254108c51b5 --- /dev/null +++ b/zig/src/hip/raw.zig @@ -0,0 +1,39 @@ +//! Device copies and fills on a forward's raw stream handle; the counting stream runs none of them. +const abi = @import("abi.zig"); +const runtime = @import("runtime.zig"); +const DeviceBuffer = @import("memory.zig").DeviceBuffer; +const counting = @import("launches/util.zig").counting; + +/// `n` bytes from device address `src` into `dst` at `offset`, queued on `stream`. +pub fn copy(dst: DeviceBuffer, offset: usize, src: u64, n: usize, stream: abi.Stream) runtime.Error!void { + if (offset > dst.len or n > dst.len - offset) return error.Invalid; + if (n == 0 or stream == counting) return; + try runtime.check(dst.r.api.hipMemcpyDtoDAsync(@ptrFromInt(dst.base() + offset), @ptrFromInt(src), n, stream)); +} + +/// Every byte of `b` set to `value`, queued on `stream`. +pub fn fill8(b: DeviceBuffer, value: u8, stream: abi.Stream) runtime.Error!void { + if (b.len == 0 or stream == counting) return; + try runtime.check(b.r.api.hipMemsetAsync(b.ptr, value, b.len, stream)); +} + +/// Every 32-bit word of `b` set to `value`, queued on `stream`. +pub fn fill32(b: DeviceBuffer, value: u32, stream: abi.Stream) runtime.Error!void { + if (b.len % 4 != 0) return error.Invalid; + if (b.len == 0 or stream == counting) return; + try runtime.check(b.r.api.hipMemsetD32Async(b.ptr, @bitCast(value), b.len / 4, stream)); +} + +/// Pinned host `bytes` into `dst` at `offset`, queued on `stream`; they stay unchanged until it completes. +pub fn upload(dst: DeviceBuffer, offset: usize, bytes: []const u8, stream: abi.Stream) runtime.Error!void { + if (offset > dst.len or bytes.len > dst.len - offset) return error.Invalid; + if (bytes.len == 0 or stream == counting) return; + try runtime.check(dst.r.api.hipMemcpyHtoDAsync(@ptrFromInt(dst.base() + offset), bytes.ptr, bytes.len, stream)); +} + +/// `out.len` bytes of `src` from `offset` into pinned host `out`, queued on `stream`. +pub fn download(src: DeviceBuffer, offset: usize, out: []u8, stream: abi.Stream) runtime.Error!void { + if (offset > src.len or out.len > src.len - offset) return error.Invalid; + if (out.len == 0 or stream == counting) return; + try runtime.check(src.r.api.hipMemcpyDtoHAsync(out.ptr, @ptrFromInt(src.base() + offset), out.len, stream)); +} diff --git a/zig/src/hip/root.zig b/zig/src/hip/root.zig new file mode 100644 index 00000000000..b9d896102a3 --- /dev/null +++ b/zig/src/hip/root.zig @@ -0,0 +1,45 @@ +//! The HIP backend as one module: runtime, the model-free kernels' launches and ops, and what an engine opens. + +pub const abi = @import("abi.zig"); +pub const runtime = @import("runtime.zig"); +pub const Runtime = runtime.Runtime; +pub const Error = runtime.Error; +pub const Context = @import("context.zig").Context; +pub const memory = @import("memory.zig"); +pub const DeviceBuffer = memory.DeviceBuffer; +pub const HostBuffer = memory.HostBuffer; +pub const usage = memory.usage; +pub const Usage = memory.Usage; +pub const Stream = @import("stream.zig").Stream; +pub const Module = @import("module.zig").Module; +pub const Function = @import("module.zig").Function; +pub const launch = @import("launch.zig"); +pub const graph = @import("graph.zig"); +pub const Arena = @import("arena.zig").Arena; +pub const caps = @import("caps.zig"); +pub const Caps = caps.Caps; +pub const kernels = @import("kernels.zig"); +pub const launches = @import("launches.zig"); +pub const Launcher = launches.Launcher; +/// The stream handle a dry run passes: launches do nothing on it. +pub const counting = @import("launches/util.zig").counting; +pub const raw = @import("raw.zig"); +pub const ops = @import("ops/ops.zig"); +pub const plan_ops = @import("ops/plan.zig"); +pub const policy = @import("policy.zig"); +pub const Policy = policy.Policy; +pub const admission = @import("admission.zig"); +pub const Device = @import("device.zig").Device; +pub const Upload = @import("upload.zig").Upload; +pub const quant = @import("core").quant; +pub const registry = @import("core").registry; +pub const collective = @import("collective.zig"); +/// Joins this rank's tensor-parallel group; this build has no collectives backend, so one rank only. +pub const joinGroup = collective.noGroup; + +test { + _ = policy; + _ = admission; + _ = Device; + _ = collective; +} diff --git a/zig/src/hip/runtime.zig b/zig/src/hip/runtime.zig index 8f5527bd844..690665c336c 100644 --- a/zig/src/hip/runtime.zig +++ b/zig/src/hip/runtime.zig @@ -25,6 +25,13 @@ pub const Runtime = struct { return std.mem.span(name); } + /// The GPUs this process sees. + pub fn deviceCount(self: *const Runtime) Error!c_int { + var n: c_int = 0; + try check(self.api.hipGetDeviceCount(&n)); + return n; + } + 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 d4b0ebfc23d..69443e3fbad 100644 --- a/zig/src/hip/runtime_tests.zig +++ b/zig/src/hip/runtime_tests.zig @@ -369,3 +369,7 @@ test "memory info sees a new allocation" { try std.testing.expectEqual(before.total, after.total); try std.testing.expect(after.free + len <= before.free); } + +test { + _ = @import("engine_runtime_tests.zig"); +} diff --git a/zig/src/hip/tuning/gfx1030.zon b/zig/src/hip/tuning/gfx1030.zon new file mode 100644 index 00000000000..a420e64cb4b --- /dev/null +++ b/zig/src/hip/tuning/gfx1030.zon @@ -0,0 +1,46 @@ +// The kernel registry's costs on RDNA2 (fp16 activations, dot2 tiles, no matrix cores). +// +// An entry is `mlx...`. Among the entries that take a product the cheapest one runs; an entry not listed +// here is not tuned for this GPU and never runs on it. Beside its `cost` an entry says which products it takes: +// rows the most rows of a plain product (0: any), and rows_matrix the most when the matrix cores take the rows above it +// min_rows the fewest rows +// items the most items of a routed plan (0: any) +// plain, routed whether it takes plain products, routed plans (both by default) +// The numbers are the thresholds the launches kept before the registry; a measured table replaces them. +.{ + .gfx = "gfx1030", + .entries = .{ + // a lane round, or a call of few rows: the stream tile takes every product it can + .{ .id = "mlx.project.decode.split", .cost = 0 }, + .{ .id = "mlx.project.decode.stream", .cost = 1, .rows = 16 }, + .{ .id = "mlx.project.decode.row", .cost = 2 }, + .{ .id = "mlx.project.decode.lanes", .cost = 3, .rows = 8 }, + .{ .id = "mlx.project.decode.wide", .cost = 4, .min_rows = 9 }, + .{ .id = "mlx.project.decode.gemm", .cost = 6, .min_rows = 64 }, + .{ .id = "mlx.project.decode.block", .cost = 7, .min_rows = 64 }, + .{ .id = "mlx.project.decode.tiled", .cost = 8 }, + .{ .id = "mlx.project.decode.reference", .cost = 9 }, + + .{ .id = "mlx.group.decode.stream", .cost = 1, .rows = 16 }, + .{ .id = "mlx.routed.decode.stream", .cost = 1, .rows = 16 }, + .{ .id = "mlx.routed.decode.row", .cost = 2 }, + .{ .id = "mlx.routed.decode.lanes", .cost = 3, .rows = 8 }, + .{ .id = "mlx.routed.decode.gemm", .cost = 6, .min_rows = 9 }, + .{ .id = "mlx.routed.decode.block", .cost = 7, .min_rows = 9 }, + .{ .id = "mlx.routed_act.decode.stream", .cost = 1, .rows = 16 }, + + // a prompt: the K-parallel tiles for a few rows or a short plan, the 128-row tile past them + .{ .id = "mlx.project.prefill.kp0", .cost = 1, .rows = 2, .routed = false }, + .{ .id = "mlx.project.prefill.kp3", .cost = 2, .items = 300, .plain = false }, + .{ .id = "mlx.project.prefill.kp1", .cost = 3, .rows = 4, .items = 410 }, + .{ .id = "mlx.project.prefill.kp2", .cost = 4, .rows = 32, .routed = false }, + .{ .id = "mlx.project.prefill.gemm", .cost = 11 }, + .{ .id = "mlx.project.prefill.block", .cost = 12 }, + .{ .id = "mlx.routed.prefill.kp0", .cost = 1, .rows = 2, .routed = false }, + .{ .id = "mlx.routed.prefill.kp3", .cost = 2, .items = 300, .plain = false }, + .{ .id = "mlx.routed.prefill.kp1", .cost = 3, .rows = 4, .items = 410 }, + .{ .id = "mlx.routed.prefill.kp2", .cost = 4, .rows = 32, .routed = false }, + .{ .id = "mlx.routed.prefill.gemm", .cost = 11 }, + .{ .id = "mlx.routed.prefill.block", .cost = 12 }, + }, +} diff --git a/zig/src/hip/tuning/gfx1100.zon b/zig/src/hip/tuning/gfx1100.zon new file mode 100644 index 00000000000..462330a8b18 --- /dev/null +++ b/zig/src/hip/tuning/gfx1100.zon @@ -0,0 +1,46 @@ +// The kernel registry's costs on RDNA3 and RDNA3.5 (bf16 activations, dot2 tiles and the gfx11 matrix cores). +// +// An entry is `mlx...`. Among the entries that take a product the cheapest one runs; an entry not listed +// here is not tuned for this GPU and never runs on it. Beside its `cost` an entry says which products it takes: +// rows the most rows of a plain product (0: any), and rows_matrix the most when the matrix cores take the rows above it +// min_rows the fewest rows +// items the most items of a routed plan (0: any) +// plain, routed whether it takes plain products, routed plans (both by default) +// The numbers are the thresholds the launches kept before the registry; a measured table replaces them. +.{ + .gfx = "gfx1100", + .entries = .{ + // a lane round, or a call of few rows: the stream tile takes every product it can; the matrix cores take 16 rows and more + .{ .id = "mlx.project.decode.stream", .cost = 1, .rows = 16, .rows_matrix = 15 }, + .{ .id = "mlx.project.decode.row", .cost = 2 }, + .{ .id = "mlx.project.decode.lanes", .cost = 3, .rows = 8 }, + .{ .id = "mlx.project.decode.matrix", .cost = 5, .min_rows = 16 }, + .{ .id = "mlx.project.decode.gemm", .cost = 6, .min_rows = 9 }, + .{ .id = "mlx.project.decode.block", .cost = 7, .min_rows = 9 }, + + .{ .id = "mlx.group.decode.stream", .cost = 1, .rows = 16, .rows_matrix = 15 }, + .{ .id = "mlx.routed.decode.stream", .cost = 1, .rows = 16, .rows_matrix = 15 }, + .{ .id = "mlx.routed.decode.row", .cost = 2 }, + .{ .id = "mlx.routed.decode.lanes", .cost = 3, .rows = 8 }, + .{ .id = "mlx.routed.decode.matrix", .cost = 5, .min_rows = 16 }, + .{ .id = "mlx.routed.decode.gemm", .cost = 6, .min_rows = 9 }, + .{ .id = "mlx.routed.decode.block", .cost = 7, .min_rows = 9 }, + .{ .id = "mlx.routed_act.decode.stream", .cost = 1, .rows = 16, .rows_matrix = 15 }, + + // a prompt: the K-parallel tiles for a few rows or a short plan, the 128-row tile past them + .{ .id = "mlx.project.prefill.kp0", .cost = 1, .rows = 2, .routed = false }, + .{ .id = "mlx.project.prefill.kp3", .cost = 2, .items = 300, .plain = false }, + .{ .id = "mlx.project.prefill.kp1", .cost = 3, .rows = 4, .items = 300 }, + .{ .id = "mlx.project.prefill.kp2", .cost = 4, .rows = 32, .routed = false }, + .{ .id = "mlx.project.prefill.matrix", .cost = 10 }, + .{ .id = "mlx.project.prefill.gemm", .cost = 11 }, + .{ .id = "mlx.project.prefill.block", .cost = 12 }, + .{ .id = "mlx.routed.prefill.kp0", .cost = 1, .rows = 2, .routed = false }, + .{ .id = "mlx.routed.prefill.kp3", .cost = 2, .items = 300, .plain = false }, + .{ .id = "mlx.routed.prefill.kp1", .cost = 3, .rows = 4, .items = 300 }, + .{ .id = "mlx.routed.prefill.kp2", .cost = 4, .rows = 32, .routed = false }, + .{ .id = "mlx.routed.prefill.matrix", .cost = 10 }, + .{ .id = "mlx.routed.prefill.gemm", .cost = 11 }, + .{ .id = "mlx.routed.prefill.block", .cost = 12 }, + }, +} diff --git a/zig/src/hip/tuning/tuning.zig b/zig/src/hip/tuning/tuning.zig new file mode 100644 index 00000000000..fbde326f2cb --- /dev/null +++ b/zig/src/hip/tuning/tuning.zig @@ -0,0 +1,21 @@ +//! The registry's costs on each GPU: the .zon tables beside this file, read at build time. + +const std = @import("std"); +const tuning = @import("core").tuning; + +pub const Row = tuning.Row; +pub const Table = tuning.Table; +pub const find = tuning.find; + +pub const gfx1030 = tuning.build(@import("gfx1030.zon")); +pub const gfx1100 = tuning.build(@import("gfx1100.zon")); + +test "the tables name each entry once" { + for ([_]*const Table{ &gfx1030, &gfx1100 }) |t| { + for (t.rows, 0..) |r, i| { + for (t.rows[i + 1 ..]) |o| try std.testing.expect(!std.mem.eql(u8, r.id, o.id)); + } + } + try std.testing.expect(find(&gfx1100, "mlx.project.decode.matrix") != null); + try std.testing.expect(find(&gfx1030, "mlx.project.decode.matrix") == null); +} diff --git a/zig/src/hip/upload.zig b/zig/src/hip/upload.zig new file mode 100644 index 00000000000..c32867f4702 --- /dev/null +++ b/zig/src/hip/upload.zig @@ -0,0 +1,26 @@ +//! The HIP backend's side of a format's `load`: host tensors onto the device, kept for the model to free. + +const std = @import("std"); +const quant = @import("core").quant; +const runtime = @import("runtime.zig"); +const memory = @import("memory.zig"); + +/// Device memory of one model: every buffer a format uploads is kept in `buffers`, which the model frees. +pub const Upload = struct { + r: *const runtime.Runtime, + buffers: *std.ArrayList(memory.DeviceBuffer), + gpa: std.mem.Allocator, + + /// What a format's `upload` takes. + pub fn uploader(u: *const Upload) quant.Uploader { + return .{ .ctx = @ptrCast(@constCast(u)), .put = put }; + } + + fn put(ctx: *anyopaque, t: quant.Tensor) anyerror!quant.Buf { + const u: *const Upload = @ptrCast(@alignCast(ctx)); + var b = try memory.DeviceBuffer.fromHost(u.r, t.bytes); + errdefer b.free(); + try u.buffers.append(u.gpa, b); + return .{ .ptr = @intFromPtr(b.ptr), .len = b.len, .dtype = t.dtype, .rank = t.rank, .shape = t.shape }; + } +}; diff --git a/zig/src/native/hip.zig b/zig/src/native/hip.zig new file mode 100644 index 00000000000..0ae934640a1 --- /dev/null +++ b/zig/src/native/hip.zig @@ -0,0 +1,255 @@ +//! The engines a native server opens on HIP: the GPU, its policy, the tensor-parallel group, round loop and lane host. + +const std = @import("std"); +const hip = @import("hip"); +const api = @import("engine_api"); +const lanes = @import("lanes"); +const qwen35 = @import("qwen3_5"); +const Allocator = std.mem.Allocator; +const admission = hip.admission; +const modelContext = admission.modelContext; + +/// The HIP families: namespaces with `model_type`, `formats`, `default_context`, `prefill_step`, `open` and `follow`. +const registry = .{ qwen35.native, qwen35.native_moe }; + +pub const backends: []const []const u8 = &.{"hip"}; +/// The serve flags past the common ones this backend takes (server/cli.zig lists and parses them). +pub const serves: []const []const u8 = &.{ "--policy", "--mtp-drafts", "--mtp-confidence", "--checkpoint-slots", "--backend=rocm" }; +pub const families: []const api.Family = blk: { + var out: [registry.len]api.Family = undefined; + for (registry, 0..) |F, i| out[i] = .{ .model_type = F.model_type, .formats = F.formats }; + const final = out; + break :blk &final; +}; + +/// The GPU family gate entries name ("rdna2" for gfx103x, "rdna3" for gfx11 / gfx12); null without a usable GPU. +pub fn chip(a: Allocator) ?[]const u8 { + const caps = hip.Device.capsOf(0) orelse return null; + return a.dupe(u8, if (caps.generation == .rdna2) "rdna2" else "rdna3") catch null; +} + +/// A flag or a resource the engine cannot take: `problem` says why. +const Refused = error{Refused}; + +fn refuse(a: Allocator, problem: *[]const u8, comptime fmt: []const u8, args: anytype) Refused { + problem.* = std.fmt.allocPrint(a, fmt, args) catch fmt; + return error.Refused; +} + +/// Why `matrix=on` cannot run on a GPU of `caps`, or null when its matrix-core tiles exist (gfx11's WMMA). +fn matrixRefused(policy: hip.Policy, caps: hip.Caps) ?[]const u8 { + if (policy.matrix != .on) return null; + return switch (caps.matrix) { + .wmma11 => null, + .wmma12 => "the gfx12 matrix-core tiles (RDNA4's WMMA layout) are not implemented yet", + .none => "this GPU has no matrix cores", + }; +} + +/// The tensor-parallel flags as the Python ROCm server checks them. +fn checkGroup(a: Allocator, o: api.Open, problem: *[]const u8) Refused!void { + if (o.tp != 1 and o.tp != 2 and o.tp != 4 and o.tp != 8) return refuse(a, problem, "--tp {d} is not a supported ROCm world size; choose 1, 2, 4 or 8", .{o.tp}); + if (o.tp > 1 and o.master.len == 0) return refuse(a, problem, "--tp > 1 needs --master: rank 0's address on the link between the machines", .{}); + // the two-Mac engines take their ranks from --speed-up's settings file; this engine takes them from --tp + if (o.speed_up != null) return refuse(a, problem, "--speed-up is the two-Mac engines' rank settings; the HIP engine takes its ranks from --tp", .{}); + if (o.tp == 1 and o.rank != 0) return refuse(a, problem, "--rank must be 0 when --tp 1", .{}); + if (o.rank >= o.tp) return refuse(a, problem, "--rank {d} not in [0, --tp {d})", .{ o.rank, o.tp }); + if (o.keep) |n| if (n < 0) return refuse(a, problem, "--checkpoint-slots must be 0 or more", .{}); + if (o.mtp_drafts) |n| if (n > 3) return refuse(a, problem, "--mtp-drafts {d}: the HIP engine drafts at most 3", .{n}); + if (o.mtp_confidence) |c| if (c < 0 or c > 1) return refuse(a, problem, "--mtp-confidence must be from 0 to 1", .{}); + if (o.prompt_cache_gib) |g| if (g < 0) return refuse(a, problem, "--prompt-cache-gib must be 0 or more", .{}); +} + +/// What every family needs before it loads: the card, the policy, the group, and the window and lanes asked for. +const Ready = struct { + dev: hip.Device, + options: Options, + /// The policy's line, for the server's info. + policy_line: []const u8, + + const Options = qwen35.native_engine.Options; + + fn deinit(r: Ready, gpa: Allocator) void { + gpa.free(r.policy_line); + if (r.dev.group) |g| g.close(gpa); + } +}; + +/// Resolves the policy on rank 0 (defaults, flags, old variables, TF_POLICY), joins the group, sends it to the others. +fn ready(comptime F: type, a: Allocator, gpa: Allocator, io: std.Io, o: api.Open, problem: *[]const u8) (Refused || Allocator.Error)!Ready { + try checkGroup(a, o, problem); + const native = modelContext(a, io, o.dir); + const window = admission.contextWindow(o.context, native, F.default_context) catch |err| return switch (err) { + error.Negative => refuse(a, problem, "--context {d}: a token count, or 0 for the model's window", .{o.context.?}), + error.NoNative => refuse(a, problem, "--context 0 asks for the model's window, and its config.json names none: give a token count", .{}), + error.PastNative => refuse(a, problem, "--context {d} exceeds this model's {d}-token window", .{ o.context.?, native }), + }; + const index: c_int = if (o.device) |d| @intCast(d) else hip.Device.ordinal(o.rank); + const caps = hip.Device.capsOf(index) orelse return refuse(a, problem, "HIP device {d} is not a GPU this engine supports", .{index}); + var notes: hip.Policy.Notes = .{}; + var policy = hip.Policy.resolve(o.policy, .current, ¬es) catch |err| return refuse(a, problem, "the policy \"{s}\" is refused ({s})", .{ o.policy, @errorName(err) }); + if (o.mtp_drafts) |n| policy.mtp.drafts = @intCast(n); + if (o.mtp_confidence) |c| policy.mtp.confidence = c; + if (o.keep) |n| policy.slots = @intCast(@min(n, 1 << 16)); + if (matrixRefused(policy, caps)) |why| return refuse(a, problem, "matrix=on: {s}; matrix=auto runs the dot2 tiles", .{why}); + const group: ?hip.collective.Group = if (o.tp > 1) hip.joinGroup(gpa, io, o.rank, o.tp, o.master, o.master_port, caps, &policy) catch |err| return switch (err) { + error.OutOfMemory => error.OutOfMemory, + error.NoTensorParallel => refuse(a, problem, "this build has no tensor parallelism: it comes with the RCCL backend", .{}), + error.NoRccl => refuse(a, problem, "tensor parallelism needs RCCL", .{}), + error.NoId => refuse(a, problem, "RCCL gave no id", .{}), + error.MixedGpus => refuse(a, problem, "the ranks' GPUs differ: a group needs one kind of GPU", .{}), + else => refuse(a, problem, "the ranks' link at {s}:{d} failed ({s})", .{ o.master, o.master_port, @errorName(err) }), + } else null; + errdefer if (group) |g| g.close(gpa); + const policy_line = try std.fmt.allocPrint(gpa, "{f}", .{policy}); + std.debug.print("[tensorfold] HIP rank {d} of {d}: policy {s}{s} {s}\n", .{ o.rank, o.tp, policy_line, if (o.rank > 0) " (rank 0's)" else "", notes.text() }); + return .{ + .dev = .{ .index = index, .caps = caps, .policy = policy, .group = group }, + .options = .{ + .window = @intCast(window), + .streams = @max(o.lanes, 1), + .fixed = o.lanes_fixed, + .rank = o.rank, + .world = o.tp, + .cache_gib = o.prompt_cache_gib, + .cache_over_cap = o.prompt_cache_over_cap, + }, + .policy_line = policy_line, + }; +} + +/// One loaded model behind the lane host: everything the engine thread reads lives here. +const Host = struct { + gpa: Allocator, + group: ?hip.collective.Group, + policy_line: []const u8, + family: *anyopaque, + release: *const fn (*anyopaque) void, + cfg: lanes.Config, + clock: lanes.backend.WallClock, + core: lanes.Engine, + host: api.LaneHost, + + fn close(p: *anyopaque) void { + const h: *Host = @ptrCast(@alignCast(p)); + h.host.stop(); + h.core.deinit(); + h.cfg.deinit(h.gpa); + h.release(h.family); + if (h.group) |g| g.close(h.gpa); + h.gpa.free(h.policy_line); + h.gpa.destroy(h); + } +}; + +/// The device bytes this process holds and their peak, as the runtime counts them. +fn readMemory(_: ?*anyopaque, reset_peak: bool) ?api.Memory { + const u = hip.usage(reset_peak); + return .{ .active = u.device, .cache = 0, .peak = u.peak }; +} + +/// The engine for `o.dir`, or null with `problem` when no HIP family reads it; under tensor parallelism, rank 0. +pub fn open(a: Allocator, gpa: Allocator, io: std.Io, o: api.Open, problem: *[]const u8) !?api.Opened { + inline for (registry) |F| { + if (std.mem.eql(u8, o.model_type, F.model_type)) return openWith(F, a, gpa, io, o, problem); + } + problem.* = try std.fmt.allocPrint(a, "the native HIP engine has no backend for {s} checkpoints yet; serve with --engine python", .{o.model_type}); + return null; +} + +fn openWith(comptime F: type, a: Allocator, gpa: Allocator, io: std.Io, o: api.Open, problem: *[]const u8) !?api.Opened { + const r = ready(F, a, gpa, io, o, problem) catch |err| switch (err) { + error.Refused => return null, + else => |x| return x, + }; + var served = false; + defer if (!served) r.deinit(gpa); + const loaded = F.open(a, gpa, io, r.dev, o.dir, r.options, problem) catch |err| switch (err) { + error.Refused => return null, + else => |x| return x, + }; + errdefer loaded.deinit(loaded.ctx); + const h = try gpa.create(Host); + errdefer gpa.destroy(h); + h.gpa = gpa; + h.group = r.dev.group; + h.policy_line = r.policy_line; + h.family = loaded.ctx; + h.release = loaded.deinit; + h.cfg = try lanes.Config.init(gpa, loaded.facts, loaded.rows, loaded.rows - 1); + errdefer h.cfg.deinit(gpa); + h.clock = .{ .io = io }; + h.core = lanes.Engine.init(gpa, &h.cfg, loaded.backend, h.clock.clock()); + errdefer h.core.deinit(); + h.host = api.LaneHost.init(gpa, io, &h.core, .{ .lanes = @intCast(loaded.streams), .context_window = @intCast(r.options.window), .prefill_step = F.prefill_step, .policy = h.policy_line, .startup = loaded.startup, .structures = true }); + h.host.memory = .{ .read = readMemory }; + try h.host.start(); + served = true; + return .{ .engine = h.host.engine(), .close = Host.close, .ctx = h }; +} + +/// A rank above 0: holds its share and runs rank 0's steps until rank 0 stops; false with `problem` if it cannot start. +pub fn follow(a: Allocator, gpa: Allocator, io: std.Io, o: api.Open, problem: *[]const u8) !bool { + inline for (registry) |F| { + if (std.mem.eql(u8, o.model_type, F.model_type)) { + const r = ready(F, a, gpa, io, o, problem) catch |err| switch (err) { + error.Refused => return false, + else => |x| return x, + }; + defer r.deinit(gpa); + F.follow(a, gpa, io, r.dev, o.dir, r.options, problem) catch |err| switch (err) { + error.Refused => return false, + else => |x| return x, + }; + return true; + } + } + problem.* = try std.fmt.allocPrint(a, "the native HIP engine has no backend for {s} checkpoints yet; serve with --engine python", .{o.model_type}); + return false; +} + +test "every registered family is listed for capabilities" { + try std.testing.expectEqual(@as(usize, registry.len), families.len); + try std.testing.expectEqualStrings("qwen3_5", families[0].model_type); + try std.testing.expectEqualStrings("qwen3_5_moe", families[1].model_type); +} + +test "the group flags: one rank source, a supported world, a master past one rank, a rank inside the world" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var problem: []const u8 = ""; + const base: api.Open = .{ .dir = "d", .model_type = "qwen3_5" }; + try checkGroup(a, base, &problem); + var two = base; + two.tp = 2; + two.master = "node0"; + try checkGroup(a, two, &problem); + var speed = base; + speed.speed_up = "settings.json"; + try std.testing.expectError(error.Refused, checkGroup(a, speed, &problem)); + try std.testing.expect(std.mem.indexOf(u8, problem, "--speed-up") != null); + speed.tp = 2; + speed.master = "node0"; + try std.testing.expectError(error.Refused, checkGroup(a, speed, &problem)); + var three = two; + three.tp = 3; + try std.testing.expectError(error.Refused, checkGroup(a, three, &problem)); + var lone = two; + lone.master = ""; + try std.testing.expectError(error.Refused, checkGroup(a, lone, &problem)); + var outside = two; + outside.rank = 2; + try std.testing.expectError(error.Refused, checkGroup(a, outside, &problem)); +} + +test "matrix=on runs only where the matrix-core tiles exist; auto runs everywhere" { + var on: hip.Policy = .{}; + try on.apply("matrix=on"); + try std.testing.expect(matrixRefused(on, hip.Caps.of("gfx1100").?) == null); + try std.testing.expect(matrixRefused(on, hip.Caps.of("gfx1151").?) == null); + try std.testing.expect(std.mem.indexOf(u8, matrixRefused(on, hip.Caps.of("gfx1201").?).?, "not implemented") != null); + try std.testing.expect(matrixRefused(on, hip.Caps.of("gfx1030").?) != null); + const auto: hip.Policy = .{}; + for ([_][]const u8{ "gfx1030", "gfx1100", "gfx1151", "gfx1200", "gfx1201" }) |name| try std.testing.expect(matrixRefused(auto, hip.Caps.of(name).?) == null); +} diff --git a/zig/tests/hip/args.zig b/zig/tests/hip/args.zig new file mode 100644 index 00000000000..daabc8f6b73 --- /dev/null +++ b/zig/tests/hip/args.zig @@ -0,0 +1,121 @@ +//! The command line of `tf-hip-test`: the commands, and the old command names as aliases of them. + +const std = @import("std"); + +pub const Command = enum { runtime, kernels, bench_launches, bench_overhead, info }; + +/// What an invocation asks for, whether by the new names or an old alias. +pub const Plan = struct { + command: Command, + filter: []const u8 = "", + bench: bool = false, + oracle: ?[]const u8 = null, + reps: ?usize = null, + n: ?usize = null, +}; + +pub const Bad = error{ BadArguments, UnknownCommand }; + +fn number(text: []const u8) Bad!usize { + return std.fmt.parseInt(usize, text, 10) catch error.BadArguments; +} + +fn value(rest: []const []const u8, i: *usize) Bad![]const u8 { + i.* += 1; + if (i.* >= rest.len) return error.BadArguments; + return rest[i.*]; +} + +/// The old commands as filters of the new ones; their positional [reps] [filter] arguments are read. +fn oldAlias(cmd: []const u8, rest: []const []const u8) Bad!?Plan { + const eql = std.mem.eql; + const first: []const u8 = if (rest.len > 0) rest[0] else ""; + if (eql(u8, cmd, "info")) return .{ .command = .info }; + for ([_][]const u8{ "smoke", "graph", "cooperative", "library", "image" }) |name| { + if (eql(u8, cmd, name)) return .{ .command = .runtime, .filter = name }; + } + if (eql(u8, cmd, "affine")) return .{ .command = .kernels, .filter = "oracle", .oracle = if (rest.len > 0) first else return error.BadArguments }; + if (eql(u8, cmd, "gemm")) { + if (eql(u8, first, "sweep")) return .{ .command = .kernels, .filter = "affine sweep" }; + if (eql(u8, first, "tiers")) return .{ .command = .kernels, .filter = "rows prefill" }; + if (eql(u8, first, "short")) return .{ .command = .kernels, .filter = "affine short", .bench = true }; + return .{ .command = .kernels, .filter = "affine prefill", .bench = true }; + } + if (eql(u8, cmd, "gemv")) return .{ .command = .kernels, .filter = "affine decode", .bench = true }; + if (eql(u8, cmd, "exact")) return .{ .command = .kernels, .filter = "rows decode" }; + if (eql(u8, cmd, "gdn")) return .{ .command = .kernels, .filter = if (eql(u8, first, "bench")) "gdn bench" else "gdn", .bench = eql(u8, first, "bench") }; + if (eql(u8, cmd, "decode")) { + const which: []const u8 = if (rest.len > 1) rest[1] else ""; + const filters = [_][]const u8{ "decode router", "decode tail", "decode group", "decode pair", "decode chain" }; + for (filters) |f| if (which.len > 0 and std.mem.endsWith(u8, f, which)) return .{ .command = .kernels, .filter = f, .bench = true }; + return .{ .command = .kernels, .filter = "decode ", .bench = true }; + } + if (eql(u8, cmd, "launches")) return .{ .command = .bench_launches, .n = if (rest.len > 0) try number(first) else null, .reps = if (rest.len > 1) try number(rest[1]) else null }; + if (eql(u8, cmd, "overhead")) return .{ .command = .bench_overhead, .n = if (rest.len > 0) try number(first) else null, .reps = if (rest.len > 1) try number(rest[1]) else null }; + return null; +} + +pub fn parse(cmd: []const u8, rest: []const []const u8) Bad!Plan { + if (try oldAlias(cmd, rest)) |plan| { + std.debug.print("note: `{s}` is an alias of the {t} command, with {s}\n", .{ cmd, plan.command, if (plan.filter.len > 0) plan.filter else "all groups" }); + return plan; + } + var plan: Plan = undefined; + var i: usize = 0; + if (std.mem.eql(u8, cmd, "runtime")) { + plan = .{ .command = .runtime }; + } else if (std.mem.eql(u8, cmd, "kernels")) { + plan = .{ .command = .kernels }; + } else if (std.mem.eql(u8, cmd, "bench")) { + if (rest.len == 0) return error.BadArguments; + plan = .{ .command = if (std.mem.eql(u8, rest[0], "launches")) .bench_launches else if (std.mem.eql(u8, rest[0], "overhead")) .bench_overhead else return error.BadArguments }; + if (rest.len > 1) plan.n = try number(rest[1]); + if (rest.len > 2) plan.reps = try number(rest[2]); + return plan; + } else return error.UnknownCommand; + while (i < rest.len) : (i += 1) { + const a = rest[i]; + if (std.mem.eql(u8, a, "--filter")) { + plan.filter = try value(rest, &i); + } else if (std.mem.eql(u8, a, "--bench") and plan.command == .kernels) { + plan.bench = true; + } else if (std.mem.eql(u8, a, "--oracle") and plan.command == .kernels) { + plan.oracle = try value(rest, &i); + } else if (std.mem.eql(u8, a, "--reps") and plan.command == .kernels) { + plan.reps = try number(try value(rest, &i)); + } else return error.BadArguments; + } + return plan; +} + +test "the old names resolve to groups of the new commands" { + const a = (try oldAlias("exact", &.{})).?; + try std.testing.expectEqual(Command.kernels, a.command); + try std.testing.expectEqualStrings("rows decode", a.filter); + const g = (try oldAlias("gemm", &.{"tiers"})).?; + try std.testing.expectEqualStrings("rows prefill", g.filter); + try std.testing.expect(!g.bench); + const m = (try oldAlias("gemv", &.{"3"})).?; + try std.testing.expect(m.bench); + const d = (try oldAlias("decode", &.{ "1", "pair" })).?; + try std.testing.expectEqualStrings("decode pair", d.filter); + const f = (try oldAlias("affine", &.{"dir"})).?; + try std.testing.expectEqualStrings("dir", f.oracle.?); + try std.testing.expectError(error.BadArguments, oldAlias("affine", &.{})); + try std.testing.expect((try oldAlias("kernels", &.{})) == null); +} + +test "the new commands take their flags" { + const p = try parse("kernels", &.{ "--filter", "gdn", "--bench", "--oracle", "x", "--reps", "7" }); + try std.testing.expectEqual(Command.kernels, p.command); + try std.testing.expectEqualStrings("gdn", p.filter); + try std.testing.expect(p.bench); + try std.testing.expectEqual(@as(?usize, 7), p.reps); + const r = try parse("runtime", &.{ "--filter", "smoke" }); + try std.testing.expectEqual(Command.runtime, r.command); + try std.testing.expectError(error.BadArguments, parse("runtime", &.{"--bench"})); + const b = try parse("bench", &.{ "overhead", "500" }); + try std.testing.expectEqual(Command.bench_overhead, b.command); + try std.testing.expectEqual(@as(?usize, 500), b.n); + try std.testing.expectError(error.UnknownCommand, parse("nothing", &.{})); +} diff --git a/zig/tests/hip_kernels.md b/zig/tests/hip_kernels.md new file mode 100644 index 00000000000..87bd39deb06 --- /dev/null +++ b/zig/tests/hip_kernels.md @@ -0,0 +1,34 @@ +# HIP model-free kernels + +`zig build hip-kernel-test -Dhip-arch=gfx1100` + +The kernels a model engine composes, compiled by hipcc for one `-Dhip-arch` with the caps table's instruction +switches, embedded, and launched from Zig on #463's runtime. No model or checkpoint is involved. + +The GPU tests check: + +- Every kernel the launchers use resolves in the embedded code objects for the device's architecture. +- The planned decode walk over a permuted page table writes the flat walk's bits for 8, 6, 4 and 1 query heads + a KV head, and sits within 1e-5 of float64 at positions 0, 37, 300 and 1023. +- The 64-row prompt tile over pages writes the flat tile's bits, within the cache type's rounding of float64. +- The DeltaNet recurrence, token-serial and chunked, within 5e-3 of a float64 recurrence at 64 to 4170 tokens. +- The merged decode launches (router, residual-and-norm tails) no further from float64 than twice the launches + they replace; the merged conv split, MoE pick and gated norm writing the replaced chains' bytes. +- Casts, sums, column copies, cache writes, argmax, top-k and the MoE route giving torch's bits; silu products, + gates, the MoE activation and RoPE within one rounding of float64. +- Every MLX affine entry the GPU has (dot2 tiles, the gfx11 matrix-core GEMM tile, the K-parallel and stream tiles), + on the served models' shapes and a ragged sweep of every width and group, within the error an fp32 sum may have + against float64; entries the registry picks between by rows write equal bytes. +- A row's product writes the same bytes alone and in a round of 2 to 32 rows, dense and routed, in every prompt tile. +- Products sharing x, and the routed gate and up with its activation, in one launch no further from float64 than + twice the launches they replace. + +Build notes: + +- `-Dhipcc` and `-Dhip-include` as for `hip-gpu-test`. +- No rocWMMA: the gfx11 matrix-core tile uses the compiler's WMMA builtins, so ROCm packages without + `rocwmma/rocwmma.hpp` (Ubuntu's ROCm 7.1) build it. +- `-Dhip-device-lib=` names ROCm's device bitcode directory. The default is `/lib/llvm/amdgcn/bitcode`, + TheRock's layout; Arch's ROCm keeps it in `/amdgcn/bitcode`, and Ubuntu's packaged HIP in the LLVM clang + resource directory (`/usr/lib/llvm-21/lib/clang/21/amdgcn/bitcode` for HIP 7.1). +- No kernel includes rocWMMA, so ROCm packages without its header (Ubuntu's HIP 7.1) build them too. diff --git a/zig/tests/qwen35/check.zig b/zig/tests/qwen35/check.zig new file mode 100644 index 00000000000..d2acb9d4bc1 --- /dev/null +++ b/zig/tests/qwen35/check.zig @@ -0,0 +1,122 @@ +//! `check [--tp N --rank R] [--truth T --ids IDS] [--only invariants|accuracy|speed]`: a line a check. + +const std = @import("std"); +const qwen35 = @import("qwen3_5"); +const check_accuracy = @import("check_accuracy.zig"); +const check_ctx = @import("check_ctx.zig"); +const check_invariants = @import("check_invariants.zig"); +const check_radix = @import("check_radix.zig"); +const check_report = @import("check_report.zig"); +const check_speed = @import("check_speed.zig"); +const group_mod = @import("group.zig"); +const ids_file = @import("ids_file.zig"); +const lanes_session = @import("lanes_session.zig"); + +const Phase = enum { invariants, accuracy, speed }; + +const Options = struct { + model: []const u8, + group: group_mod.Group = .{}, + prompts: ?[]const u8 = null, + truth: ?[]const u8 = null, + ids: ?[]const u8 = null, + speed: bool = false, + explain: bool = false, + only: ?Phase = null, + tokens: u32 = 48, + bar: check_accuracy.Bar = .{}, + + fn runs(o: Options, p: Phase) bool { + if (o.only) |only| return only == p; + return switch (p) { + .invariants => true, + .accuracy => o.truth != null, + .speed => o.speed, + }; + } +}; + +fn parse(args: []const [:0]const u8) !Options { + if (args.len < 1) return error.MissingArgument; + var o: Options = .{ .model = args[0] }; + var i: usize = 1; + while (i < args.len) : (i += 1) { + if (try o.group.option(args, &i)) continue; + const a = args[i]; + if (std.mem.eql(u8, a, "--speed")) { + o.speed = true; + continue; + } + if (std.mem.eql(u8, a, "--explain-kernels")) { + o.explain = true; + continue; + } + i += 1; + if (i >= args.len) return error.MissingArgument; + if (std.mem.eql(u8, a, "--prompts")) o.prompts = args[i] else if (std.mem.eql(u8, a, "--truth")) o.truth = args[i] else if (std.mem.eql(u8, a, "--ids")) o.ids = args[i] else if (std.mem.eql(u8, a, "--only")) o.only = std.meta.stringToEnum(Phase, args[i]) orelse return error.UnknownPhase else if (std.mem.eql(u8, a, "--tokens")) o.tokens = try std.fmt.parseInt(u32, args[i], 10) else if (std.mem.eql(u8, a, "--kl")) o.bar.kl_mean = try std.fmt.parseFloat(f64, args[i]) else if (std.mem.eql(u8, a, "--top1")) o.bar.top1 = try std.fmt.parseFloat(f64, args[i]) else return error.UnknownOption; + } + if (o.runs(.accuracy) and o.truth == null and !o.explain) return error.NoTruth; + return o; +} + +/// The ids file the truth was made from, next to it, when none is given. +fn idsPath(arena: std.mem.Allocator, o: Options) !?[]const u8 { + if (o.ids) |p| return p; + const t = o.truth orelse return null; + const stem = if (std.mem.endsWith(u8, t, ".npy")) t[0 .. t.len - 4] else t; + return try std.fmt.allocPrint(arena, "{s}.ids.npy", .{stem}); +} + +/// Pages of the largest phase (four streams at the capacity, or the radix streams and tree) and the padding slot's. +fn poolPages(capacity: usize, tokens: u32) usize { + const pages = qwen35.pages.pagesFor; + const radix = check_radix.most_streams * pages(check_radix.capacity(tokens)) + check_radix.tree_pages; + return @max(4 * pages(capacity), radix) + pages(rows); +} + +/// Rows a round of the checks holds at most: four streams of the widest window. +const rows = 4 * qwen35.hip_lanes.Hip.max_window; + +/// Exit code: 0 when every check passed (or skipped), 1 when one failed. +pub fn run(gpa: std.mem.Allocator, io: std.Io, args: []const [:0]const u8) !u8 { + var arena_state = std.heap.ArenaAllocator.init(gpa); + defer arena_state.deinit(); + const arena = arena_state.allocator(); + const o = try parse(args); + const ids = if (try idsPath(arena, o)) |p| try ids_file.load(arena, io, p) else try ids_file.synthetic(arena, 1536); + const short = try ids_file.short(arena); + const long = if (o.prompts) |p| try ids_file.read(arena, io, p) else try ids_file.long(arena, ids); + + var capacity = ids_file.longest(long) + 2 * o.tokens + 64; + capacity = @max(capacity, check_radix.capacity(o.tokens)); + if (o.runs(.accuracy)) capacity = @max(capacity, ids.len + 64); + if (o.runs(.speed)) capacity = @max(capacity, check_speed.longest_prefill + 64); + var joined = try o.group.join(gpa, io); + defer joined.close(); + const e = try o.group.engine(gpa, io, o.model, joined, .{ .capacity = capacity, .prompt_rows = capacity, .streams = check_radix.most_streams, .snapshots = check_radix.slots, .batch_rows = rows, .pool_pages = poolPages(capacity, o.tokens) }); + defer e.deinit(); + if (o.group.rank > 0) { + try group_mod.follow(gpa, e, &joined); + return 0; + } + if (o.explain) { + var buf: [4096]u8 = undefined; + var w: std.Io.Writer = .fixed(&buf); + try e.lib.affine.reg.explain(e.lib.affine.env(), .mlx, &w, e.weights.spec.bits, e.weights.spec.group); + std.debug.print("{s}", .{w.buffered()}); + return 0; + } + var session: lanes_session.Session = undefined; + try session.init(gpa, io, e, joined.link()); + defer session.deinit(); + + var report: check_report.Report = .{}; + var c: check_ctx.Ctx = .{ .gpa = gpa, .io = io, .arena = arena, .e = e, .session = &session, .report = &report, .group = o.group, .ids = ids, .short = short, .long = long, .tokens = o.tokens, .pages_at_start = e.pool.ids.used() }; + const t0 = std.Io.Clock.awake.now(io); + std.debug.print("check {s}, tp {d}\n", .{ o.model, o.group.world }); + if (o.runs(.invariants)) check_invariants.run(&c); + if (o.runs(.accuracy)) check_accuracy.run(&c, o.truth.?, o.bar); + if (o.runs(.speed)) check_speed.run(&c); + report.summary(@as(f64, @floatFromInt(std.Io.Clock.awake.now(io).toNanoseconds() - t0.toNanoseconds())) / 1e9); + return if (report.failed == 0) 0 else 1; +} diff --git a/zig/tests/qwen35/check_accuracy.zig b/zig/tests/qwen35/check_accuracy.zig new file mode 100644 index 00000000000..22c4c5ef2f6 --- /dev/null +++ b/zig/tests/qwen35/check_accuracy.zig @@ -0,0 +1,34 @@ +//! The accuracy checks of `check`: every row's logits, from a cold prefill and from decode rounds, against fp64 truth. + +const std = @import("std"); +const check_ctx = @import("check_ctx.zig"); +const logits_run = @import("logits_run.zig"); +const truth_score = @import("truth_score.zig"); + +const Ctx = check_ctx.Ctx; + +/// What a score must stay within. +pub const Bar = struct { kl_mean: f64 = 0.01, top1: f64 = 90.0, ppl_ratio: f64 = 1.02 }; + +pub fn run(c: *Ctx, truth: []const u8, bar: Bar) void { + if (c.tp()) return c.report.skip("accuracy", "the logits run on one rank"); + const mode0: logits_run.Mode = .{ .wide = true }; + var scorer = truth_score.Scorer.init(c.gpa, c.io, truth, c.ids, logits_run.kindOf(c.e, mode0), logits_run.vocab(c.e)) catch |err| return c.report.broke("accuracy", err); + defer scorer.deinit(); + for ([_]bool{ false, true }) |decode| { + const name = if (decode) "accuracy decode" else "accuracy prefill"; + scorer.reset(); + logits_run.stream(c.gpa, c.e, c.ids, .{ .wide = true, .decode = decode }, .{ .ctx = &scorer, .put = truth_score.Scorer.put }) catch |err| { + c.report.broke(name, err); + continue; + }; + const s = scorer.result() catch |err| { + c.report.broke(name, err); + continue; + }; + const ok = s.kl_mean <= bar.kl_mean and s.top1 >= bar.top1 and s.ppl <= s.ppl_truth * bar.ppl_ratio; + const line = "rows={d} KL mean={e:.3} max={e:.3} top1={d:.2}% max|dlogit|={d:.4} ppl truth={d:.4} cand={d:.4}"; + const args = .{ s.rows, s.kl_mean, s.kl_max, s.top1, s.max_abs, s.ppl_truth, s.ppl }; + if (ok) c.report.pass(name, line, args) else c.report.fail(name, line ++ " (bar: KL mean <= {e:.1}, top1 >= {d:.0}%, ppl within {d:.0}%)", args ++ .{ bar.kl_mean, bar.top1, (bar.ppl_ratio - 1) * 100 }); + } +} diff --git a/zig/tests/qwen35/check_ctx.zig b/zig/tests/qwen35/check_ctx.zig new file mode 100644 index 00000000000..cb5ec1120d9 --- /dev/null +++ b/zig/tests/qwen35/check_ctx.zig @@ -0,0 +1,41 @@ +//! What the checks of one `check` run share: the engine, its lane session, the prompts and the report. + +const std = @import("std"); +const lanes = @import("lanes"); +const qwen35 = @import("qwen3_5"); +const group_mod = @import("group.zig"); +const ids_file = @import("ids_file.zig"); +const lanes_session = @import("lanes_session.zig"); +const check_report = @import("check_report.zig"); + +pub const Ctx = struct { + gpa: std.mem.Allocator, + io: std.Io, + /// Lives to the end of the run: replies, prompt sets. + arena: std.mem.Allocator, + e: *qwen35.engine.Engine, + session: *lanes_session.Session, + report: *check_report.Report, + group: group_mod.Group, + /// Ids for the long prompts, the row cases and the accuracy rows. + ids: []const u32, + short: []const ids_file.Prompt, + long: []const ids_file.Prompt, + /// Tokens each stream of an invariant run generates. + tokens: u32, + /// Pages the pool held before the first run: the scratch rows'. + pages_at_start: usize = 0, + + /// Whether this run spans GPUs, where only what the lane core drives can run. + pub fn tp(c: *const Ctx) bool { + return c.group.world > 1; + } +}; + +/// The ways a stream draws its tokens. +pub const Draw = struct { name: []const u8, sampling: ?lanes.Sampling }; + +pub const draws = [_]Draw{ + .{ .name = "greedy", .sampling = null }, + .{ .name = "seeded t=1", .sampling = .{ .seed = 7, .temperature = 1.0 } }, +}; diff --git a/zig/tests/qwen35/check_invariants.zig b/zig/tests/qwen35/check_invariants.zig new file mode 100644 index 00000000000..aaaa3907308 --- /dev/null +++ b/zig/tests/qwen35/check_invariants.zig @@ -0,0 +1,139 @@ +//! The exactness checks of `check`: windows, drafts, shared rounds, resumed prompts and replayed graphs against serial. + +const std = @import("std"); +const check_ctx = @import("check_ctx.zig"); +const ids_file = @import("ids_file.zig"); +const lanes_session = @import("lanes_session.zig"); +const rows_run = @import("rows_run.zig"); +const check_radix = @import("check_radix.zig"); + +const Ctx = check_ctx.Ctx; +const Session = lanes_session.Session; + +/// Windows of 1 to 16 rows, streams with a rejected draft's partial keep, and rounds padded up to a bucket. +const cases = blk: { + var list: [25]rows_run.Case = undefined; + for (0..16) |i| list[i] = .{ .streams = 1, .n = i + 1, .keep = i + 1 }; + list[16] = .{ .streams = 4, .n = 4, .keep = 4 }; + list[17] = .{ .streams = 4, .n = 4, .keep = 2 }; + list[18] = .{ .streams = 4, .n = 2, .keep = 2 }; + list[19] = .{ .streams = 4, .n = 2, .keep = 1 }; + list[20] = .{ .streams = 1, .n = 1, .keep = 1, .pad = 4 }; + list[21] = .{ .streams = 1, .n = 3, .keep = 3, .pad = 8 }; + list[22] = .{ .streams = 3, .n = 3, .keep = 2, .pad = 16 }; + list[23] = .{ .streams = 4, .n = 4, .keep = 4, .pad = 32 }; + list[24] = .{ .streams = 2, .n = 4, .keep = 1, .pad = 64 }; + break :blk list; +}; + +pub fn run(c: *Ctx) void { + rows(c); + lanesSet(c, "short", c.short); + lanesSet(c, "long", c.long); + resumed(c); + check_radix.run(c); + replayShare(c); + check_radix.leaked(c); +} + +fn rows(c: *Ctx) void { + if (c.tp()) return c.report.skip("rows", "the layer by layer trace runs on one rank; the lane checks below run the windows under tp"); + const ids = c.ids[0..@min(c.ids.len, 256)]; + for (cases) |k| { + const plain = std.fmt.allocPrint(c.arena, "rows {d} stream{s} x {d} row{s}, {d} kept", .{ k.streams, if (k.streams == 1) "" else "s", k.n, if (k.n == 1) "" else "s", k.keep }) catch return; + const name = if (k.pad > 0) std.fmt.allocPrint(c.arena, "{s}, padded to {d}", .{ plain, k.pad }) catch return else plain; + const diff = rows_run.runCase(c.gpa, c.e, ids, k) catch |err| { + c.report.broke(name, err); + continue; + }; + if (diff) |d| { + c.report.fail(name, "layer {d} ({s}), stream {d} row {d}: first difference at column {d}", .{ d.layer, d.kind, d.stream, d.row, d.column }); + } else c.report.pass(name, "every layer's residuals and the final rows equal each stream one row at a time", .{}); + } +} + +/// Where two runs' replies first differ, as a line to print; null when they are equal. +fn differ(a: Session.Done, b: Session.Done, buf: []u8) ?[]const u8 { + for (a.replies, b.replies) |x, y| { + const at = std.mem.indexOfDiff(u32, x.tokens, y.tokens) orelse continue; + const xt: i64 = if (at < x.tokens.len) x.tokens[at] else -1; + const yt: i64 = if (at < y.tokens.len) y.tokens[at] else -1; + return std.fmt.bufPrint(buf, "{s} differs at token {d}: {d} against {d}", .{ x.name, at, xt, yt }) catch "differs"; + } + return null; +} + +fn verdict(c: *Ctx, name: []const u8, a: Session.Done, b: Session.Done) void { + var buf: [160]u8 = undefined; + if (differ(a, b, &buf)) |why| return c.report.fail(name, "{s}", .{why}); + c.report.pass(name, "{d} streams, {d} tokens, {d} drafts accepted", .{ a.replies.len, a.tokens(), a.accepted() }); +} + +fn named(c: *Ctx, comptime fmt: []const u8, args: anytype) []const u8 { + return std.fmt.allocPrint(c.arena, fmt, args) catch "lanes"; +} + +/// Drafted against serial, solo against together and graph against eager, for each way of drawing. +fn lanesSet(c: *Ctx, set: []const u8, prompts: []const ids_file.Prompt) void { + for (check_ctx.draws) |d| { + const job: Session.Job = .{ .prompts = prompts, .max_new = c.tokens, .sampling = d.sampling }; + const together = c.session.run(c.arena, job) catch |err| return c.report.broke(named(c, "lanes {s} {s}", .{ set, d.name }), err); + var serial = job; + serial.drafts = false; + const drafted = named(c, "lanes {s} {s}: drafted == serial", .{ set, d.name }); + if (c.session.h.head == null) { + c.report.skip(drafted, "the model has no draft head"); + } else if (c.session.run(c.arena, serial)) |done| verdict(c, drafted, together, done) else |err| c.report.broke(drafted, err); + var solo = job; + solo.solo = true; + if (c.session.run(c.arena, solo)) |done| verdict(c, named(c, "lanes {s} {s}: solo == together", .{ set, d.name }), together, done) else |err| c.report.broke(named(c, "lanes {s} {s}: solo == together", .{ set, d.name }), err); + graphs(c, named(c, "lanes {s} {s}: graph == eager", .{ set, d.name }), job, together); + } +} + +/// `graph` ran with the engine's graphs; the same job again with every round eager. +fn graphs(c: *Ctx, name: []const u8, job: Session.Job, graph: Session.Done) void { + if (c.tp()) return c.report.skip(name, "rounds under tp run eager unless --policy graphs=on"); + if (!c.e.o.graphs) return c.report.skip(name, "graphs are off"); + if (graph.replayed == 0) return c.report.skip(name, "no round of the run replayed a graph"); + c.e.o.graphs = false; + defer c.e.o.graphs = true; + const eager = c.session.run(c.arena, job) catch |err| return c.report.broke(name, err); + var buf: [160]u8 = undefined; + if (differ(graph, eager, &buf)) |why| return c.report.fail(name, "{s}", .{why}); + c.report.pass(name, "{d} rounds replayed, {d} tokens", .{ graph.replayed, graph.tokens() }); +} + +/// Each long prompt again, extended by its reply, on the caches the first run kept, against a run with none kept. +fn resumed(c: *Ctx) void { + const name = "lanes long greedy: resumed == fresh"; + c.session.h.keepPrompts(8, 4 << 30); + defer c.session.h.keepPrompts(0, 0); + const first = c.session.run(c.arena, .{ .prompts = c.long, .max_new = c.tokens }) catch |err| return c.report.broke(name, err); + const extended = lanes_session.extend(c.arena, c.long, first.replies) catch |err| return c.report.broke(name, err); + const again = c.session.run(c.arena, .{ .prompts = extended, .max_new = c.tokens, .solo = true }) catch |err| return c.report.broke(name, err); + const fresh = c.session.run(c.arena, .{ .prompts = extended, .max_new = c.tokens, .solo = true, .drafts = false }) catch |err| return c.report.broke(name, err); + var cached: usize = 0; + var every = true; + for (again.replies) |r| { + cached += r.cached; + every = every and r.cached > 0; + } + var buf: [160]u8 = undefined; + if (differ(again, fresh, &buf)) |why| return c.report.fail(name, "{s}", .{why}); + if (!every) return c.report.fail(name, "a prompt resumed from no kept caches ({d} tokens kept in all)", .{cached}); + c.report.pass(name, "{d} streams, {d} tokens, {d} prompt tokens from the kept caches", .{ again.replies.len, again.tokens(), cached }); +} + +/// A drafted run of every stream at once, the third time: once its shapes are met, rounds replay graphs. +fn replayShare(c: *Ctx) void { + const name = "lanes short greedy: rounds replayed"; + if (c.tp() and !c.e.o.graphs) return c.report.skip(name, "rounds under tp run eager unless the policy says graphs=on"); + if (!c.e.o.graphs) return c.report.skip(name, "graphs are off"); + const job: Session.Job = .{ .prompts = c.short, .max_new = c.tokens }; + var done: Session.Done = undefined; + for (0..3) |_| done = c.session.run(c.arena, job) catch |err| return c.report.broke(name, err); + const share = 100.0 * @as(f64, @floatFromInt(done.replayed)) / @as(f64, @floatFromInt(@max(done.rounds, 1))); + if (share < 99.0) return c.report.fail(name, "{d:.1}% of {d} rounds replayed", .{ share, done.rounds }); + c.report.pass(name, "{d:.1}% of {d} rounds replayed, {d:.0} us a round submitting", .{ share, done.rounds, @as(f64, @floatFromInt(done.submit_ns)) / @as(f64, @floatFromInt(@max(done.rounds, 1))) / 1e3 }); +} diff --git a/zig/tests/qwen35/check_radix.zig b/zig/tests/qwen35/check_radix.zig new file mode 100644 index 00000000000..8119f81b310 --- /dev/null +++ b/zig/tests/qwen35/check_radix.zig @@ -0,0 +1,260 @@ +//! The prefix tree's checks of `check`: shared prefixes equal fresh runs, copy on write, and no page leaks. + +const std = @import("std"); +const lanes = @import("lanes"); +const qwen35 = @import("qwen3_5"); +const check_ctx = @import("check_ctx.zig"); +const ids_file = @import("ids_file.zig"); +const lanes_session = @import("lanes_session.zig"); + +const Ctx = check_ctx.Ctx; +const Prompt = ids_file.Prompt; +const Session = lanes_session.Session; +const pages = qwen35.pages; + +/// Tokens of the system prompt the requests share, and how many questions follow it. +const system_len = 1100; +const questions = 8; +/// Of those, the ones whose conversation goes on a turn. +const turns = 4; +/// Pages the tree checks leave room for beside the streams'. +pub const tree_pages = 600; +/// Snapshots the stress keeps, and the streams its last pass runs at once: every question, turn and branch. +pub const slots = 8; +pub const most_streams = questions + turns + 2; + +/// Tokens of the question of each request of the memory line, and how far apart they start. +const long_tail = 320; +const tail_step = 16; + +/// Positions the longest request of the tree checks takes, replies of `tokens` tokens included. +pub fn capacity(tokens: u32) usize { + return system_len + long_tail + 2 * tokens + 64; +} + +/// The requests the tree is built from: every one a shared system prompt and its own question. +fn singles(c: *Ctx) ![]const Prompt { + const sys = c.ids[0..system_len]; + const shared = try c.arena.dupe(u32, &.{system_len}); + const step = (c.ids.len - system_len) / questions; + const out = try c.arena.alloc(Prompt, questions); + for (out, 0..) |*p, j| { + const tail = c.ids[system_len + j * step ..][0 .. 24 + 8 * (j % 4)]; + p.* = .{ .name = try std.fmt.allocPrint(c.arena, "a{d}", .{j}), .ids = try std.mem.concat(c.arena, u32, &.{ sys, tail }), .shared = shared }; + } + return out; +} + +/// Requests that branch off the others: one inside the system prompt's last page, one in the middle of its pages. +fn branches(c: *Ctx, singles_set: []const Prompt) ![]const Prompt { + const sys = c.ids[0..system_len]; + const shared = try c.arena.dupe(u32, &.{system_len}); + const first = singles_set[0].ids[system_len..][0..20]; + const other = singles_set[questions - 1].ids[system_len..][0..30]; + const out = try c.arena.alloc(Prompt, 2); + out[0] = .{ .name = "c0", .ids = try std.mem.concat(c.arena, u32, &.{ sys, first, other }), .shared = shared }; + out[1] = .{ .name = "c1", .ids = try std.mem.concat(c.arena, u32, &.{ sys[0..640], c.ids[100..160] }) }; + return out; +} + +fn sameReplies(a: Session.Done, b: Session.Done, skip: usize, buf: []u8) ?[]const u8 { + for (a.replies[skip..], b.replies[skip..]) |x, y| { + const at = std.mem.indexOfDiff(u32, x.tokens, y.tokens) orelse continue; + return std.fmt.bufPrint(buf, "{s} differs at token {d}", .{ x.name, at }) catch "differs"; + } + return null; +} + +/// Bytes a copy of the caches at each kept mark would hold: marks past where each request resumed, repeats once. +fn copiedBytes(c: *Ctx, set: []const Prompt, replies: []const Session.Reply) usize { + const spec = c.e.model().spec; + var kept: std.ArrayList([]const u32) = .empty; + var bytes: usize = 0; + for (set, replies) |p, r| { + const marks = c.session.h.prefix.store.marks(c.arena, p.ids, r.cached, @intCast(p.ids.len / 2), p.shared, &.{}) catch return bytes; + for (marks) |m| { + const ids = p.ids[0..m]; + const known = for (kept.items) |k| { + if (std.mem.eql(u32, k, ids)) break true; + } else false; + if (known) continue; + kept.append(c.arena, ids) catch return bytes; + bytes += qwen35.memory.stateBytes(spec, c.e.model().act.size(), m); + } + } + return bytes; +} + +fn mib(bytes: usize) f64 { + return @as(f64, @floatFromInt(bytes)) / (1 << 20); +} + +pub fn run(c: *Ctx) void { + stress(c); + memoryLine(c); + if (c.tp()) { + c.report.skip("radix: a resumed page equals a fresh one", "a prompt pass runs on one rank"); + c.report.skip("radix: a shared page is copied before a write", "the copy runs on one rank"); + return; + } + resumedPages(c); + copyOnWrite(c); +} + +/// Requests branching from shared prefixes, each against its own fresh run, alone and then all together. +fn stress(c: *Ctx) void { + const name = "radix stress"; + if (c.ids.len < system_len + 8 * questions) return c.report.skip(name, "too few ids"); + const h = c.session.h; + h.keepPrompts(0, 0); + h.keepPrompts(slots, 4 << 30); + defer h.keepPrompts(0, 0); + const first = singles(c) catch |err| return c.report.broke(name, err); + const alone = c.session.run(c.arena, .{ .prompts = first, .max_new = c.tokens, .solo = true }) catch |err| return c.report.broke(name, err); + // the next turn of some conversations, and the branches + const next = lanes_session.extend(c.arena, first[0..turns], alone.replies[0..turns]) catch |err| return c.report.broke(name, err); + const branched = branches(c, first) catch |err| return c.report.broke(name, err); + const second = std.mem.concat(c.arena, Prompt, &.{ next, branched }) catch |err| return c.report.broke(name, err); + const more = c.session.run(c.arena, .{ .prompts = second, .max_new = c.tokens, .solo = true }) catch |err| return c.report.broke(name, err); + const every = std.mem.concat(c.arena, Prompt, &.{ first, second }) catch |err| return c.report.broke(name, err); + // all of them again at once, on the warm tree + const together = c.session.run(c.arena, .{ .prompts = every, .max_new = c.tokens }) catch |err| return c.report.broke(name, err); + const fresh = c.session.run(c.arena, .{ .prompts = every, .max_new = c.tokens, .solo = true, .drafts = false }) catch |err| return c.report.broke(name, err); + var buf: [128]u8 = undefined; + const label = std.fmt.allocPrint(c.arena, "radix: {d} requests, resumed == fresh", .{every.len}) catch return; + if (sameReplies(alone, .{ .replies = fresh.replies[0..first.len], .seconds = 0, .rounds = 0, .replayed = 0, .submit_ns = 0, .spent = fresh.spent, .calls = fresh.calls }, 0, &buf)) |why| return c.report.fail(label, "{s}", .{why}); + if (sameReplies(more, .{ .replies = fresh.replies[first.len..], .seconds = 0, .rounds = 0, .replayed = 0, .submit_ns = 0, .spent = fresh.spent, .calls = fresh.calls }, 0, &buf)) |why| return c.report.fail(label, "{s}", .{why}); + var resumed: usize = 0; + var edges = true; + for ([_][]const Session.Reply{ alone.replies, more.replies, together.replies }) |set| for (set) |r| { + edges = edges and r.cached % pages.tokens == 0; + resumed += @intFromBool(r.cached > 0); + }; + c.report.pass(label, "{d} of {d} resumed, {d} tokens each", .{ resumed, alone.replies.len + more.replies.len + together.replies.len, c.tokens }); + if (sameReplies(together, fresh, 0, &buf)) |why| return c.report.fail("radix: all together == fresh", "{s}", .{why}); + c.report.pass("radix: all together == fresh", "{d} streams, {d} drafts accepted", .{ together.replies.len, together.accepted() }); + if (!edges) c.report.fail("radix: spans start on page edges", "a request resumed off a page edge", .{}) else c.report.pass("radix: spans start on page edges", "every resume at a multiple of {d}", .{pages.tokens}); + // the requests after the first take the system prompt's whole pages from the tree + const want: usize = system_len / pages.tokens * pages.tokens; + var short: usize = 0; + for (alone.replies[1..]) |r| short += @intFromBool(r.cached != want); + if (short > 0) c.report.fail("radix: the system prompt is shared", "{d} of {d} requests after the first did not resume at {d}", .{ short, alone.replies.len - 1, want }) else c.report.pass("radix: the system prompt is shared", "{d} requests resumed at {d} of {d} tokens", .{ alone.replies.len - 1, want, system_len }); +} + +/// What `questions` requests sharing one system prompt leave in the tree, against per-cut copies of the caches. +fn memoryLine(c: *Ctx) void { + const name = "radix memory"; + if (c.ids.len < system_len + tail_step * questions + long_tail) return c.report.skip(name, "too few ids"); + const h = c.session.h; + h.keepPrompts(0, 0); + h.keepPrompts(2 * questions, 2 << 30); + defer h.keepPrompts(0, 0); + const sys = c.ids[0..system_len]; + const shared = c.arena.dupe(u32, &.{system_len}) catch return; + const set = c.arena.alloc(Prompt, questions) catch return; + for (set, 0..) |*p, j| { + const tail = c.ids[system_len + j * tail_step ..][0..long_tail]; + p.* = .{ .name = std.fmt.allocPrint(c.arena, "q{d}", .{j}) catch return, .ids = std.mem.concat(c.arena, u32, &.{ sys, tail }) catch return, .shared = shared }; + } + const done = c.session.run(c.arena, .{ .prompts = set, .max_new = 1, .solo = true }) catch |err| return c.report.broke(name, err); + const tree = &h.prefix.store.tree; + const copied = copiedBytes(c, set, done.replies); + const unique = pagesBytes(c, tree.held_pages); + const states = tree.held() - unique; + var cached: usize = 0; + for (done.replies) |r| cached += r.cached; + c.report.pass(name, "{d} requests sharing {d} system tokens, {d} tokens each: the tree holds {d:.1} MiB ({d} pages {d:.1} MiB, {d} snapshots {d:.1} MiB); copies of the caches at each cut held {d:.1} MiB; {d} prompt tokens came from the tree", .{ set.len, system_len, set[0].ids.len, mib(tree.held()), tree.held_pages, mib(unique), tree.snaps, mib(states), mib(copied), cached }); +} + +fn pagesBytes(c: *Ctx, n: usize) u64 { + return n * c.e.pool.pageBytes(); +} + +/// The pages of a prompt resumed from the tree hold what a fresh prefill of it writes. +fn resumedPages(c: *Ctx) void { + const name = "radix: a resumed page equals a fresh one"; + const h = c.session.h; + const e = c.e; + h.keepPrompts(0, 0); + h.keepPrompts(8, 4 << 30); + defer h.keepPrompts(0, 0); + const set = singles(c) catch |err| return c.report.broke(name, err); + // the first run keeps the system prompt, the second resumes from it + _ = c.session.run(c.arena, .{ .prompts = set[0..1], .max_new = 1, .solo = true }) catch |err| return c.report.broke(name, err); + const prompt = set[1].ids; + var st = lanes.Stream.init(c.gpa, .{ .id = "resumed", .prompt = prompt, .max_new = 1, .history_len = @intCast(prompt.len / 2), .shared_prefixes = set[1].shared }) catch |err| return c.report.broke(name, err); + defer st.deinit(c.gpa); + const be = h.backend(); + be.prefill(&st) catch |err| return c.report.broke(name, err); + defer be.release(&st); + if (st.cached == 0) return c.report.fail(name, "the prompt resumed from nothing", .{}); + const lane = h.lanes.get(&st) orelse return c.report.fail(name, "no lane", .{}); + var fresh = e.newCaches(prompt.len + 8) catch |err| return c.report.broke(name, err); + defer fresh.deinit(c.gpa); + _ = e.prefill(&fresh, prompt, 0, null, .{ .sampling = null, .position = prompt.len }, null) catch |err| return c.report.broke(name, err); + e.drain(); + const m = e.model(); + const layer_bytes = e.pool.layerBytes(); + const row = m.spec.head_dim * m.act.size(); + const mine = c.arena.alloc(u8, 2 * layer_bytes) catch return; + const theirs = c.arena.alloc(u8, 2 * layer_bytes) catch return; + var compared: usize = 0; + for (0..m.spec.n_layers) |layer| { + if (!m.spec.full(layer)) continue; + for (0..pages.pagesFor(prompt.len)) |p| { + e.pool.read(layer, lane.caches.table.items[p], mine) catch |err| return c.report.broke(name, err); + e.pool.read(layer, fresh.table.items[p], theirs) catch |err| return c.report.broke(name, err); + const used = @min(pages.tokens, prompt.len - p * pages.tokens); + for ([_]usize{ 0, layer_bytes }) |half| for (0..m.spec.kv_heads) |head| { + const at = half + head * pages.tokens * row; + if (!std.mem.eql(u8, mine[at..][0 .. used * row], theirs[at..][0 .. used * row])) return c.report.fail(name, "layer {d}, page {d}, head {d} differs", .{ layer, p, head }); + }; + compared += 1; + } + } + const per_layer = pages.pagesFor(prompt.len); + c.report.pass(name, "{d} pages of {d} tokens in each of {d} attention layers, the first {d} from the tree, all equal", .{ per_layer, prompt.len, compared / per_layer, st.cached / pages.tokens }); +} + +/// A page two streams hold is copied before one writes it, and the copy holds the same bytes. +fn copyOnWrite(c: *Ctx) void { + const name = "radix: a shared page is copied before a write"; + const e = c.e; + const m = e.model(); + const len = pages.tokens + 36; + var first = e.newCaches(2 * pages.tokens) catch |err| return c.report.broke(name, err); + defer first.deinit(c.gpa); + _ = e.prefill(&first, c.ids[0..len], 0, null, .{ .sampling = null, .position = len }, null) catch |err| return c.report.broke(name, err); + e.drain(); + var second = e.emptyCaches(2 * pages.tokens) catch |err| return c.report.broke(name, err); + defer second.deinit(c.gpa); + for (first.table.items[0..2]) |id| e.pool.retain(id); + second.set(c.gpa, 0, first.table.items[0..2]) catch |err| return c.report.broke(name, err); + var done: std.ArrayList([3]u32) = .empty; + defer done.deinit(c.gpa); + // a write at position 100 lands in the second page, which both hold + second.writable(&done, c.gpa, 100, 101, e.stream.handle) catch |err| return c.report.broke(name, err); + e.drain(); + if (done.items.len != 1 or done.items[0][0] != 1) return c.report.fail(name, "{d} pages copied", .{done.items.len}); + if (second.table.items[0] != first.table.items[0] or second.table.items[1] == first.table.items[1]) return c.report.fail(name, "the wrong pages were copied", .{}); + const layer_bytes = e.pool.layerBytes(); + const a = c.arena.alloc(u8, 2 * layer_bytes) catch return; + const b = c.arena.alloc(u8, 2 * layer_bytes) catch return; + for (0..m.spec.n_layers) |layer| { + if (!m.spec.full(layer)) continue; + e.pool.read(layer, first.table.items[1], a) catch |err| return c.report.broke(name, err); + e.pool.read(layer, second.table.items[1], b) catch |err| return c.report.broke(name, err); + if (!std.mem.eql(u8, a, b)) return c.report.fail(name, "layer {d}: the copy differs", .{layer}); + } + if (e.pool.ids.refs[first.table.items[0]] != 2 or e.pool.ids.refs[first.table.items[1]] != 1) return c.report.fail(name, "the holders were not counted", .{}); + c.report.pass(name, "page 1 copied, page 0 still shared, the copy equal in every attention layer", .{}); +} + +/// After every run the pool holds the pages it started with: no stream and no tree entry leaked one. +pub fn leaked(c: *Ctx) void { + const name = "radix: every page comes back"; + c.session.h.keepPrompts(0, 0); + const used = c.e.pool.ids.used(); + if (used != c.pages_at_start or c.e.pool.ids.reserved != 0) return c.report.fail(name, "{d} pages held and {d} promised after the runs, {d} held before", .{ used, c.e.pool.ids.reserved, c.pages_at_start }); + c.report.pass(name, "{d} of {d} pages held after the runs, as before", .{ used, c.e.pool.count }); +} diff --git a/zig/tests/qwen35/check_report.zig b/zig/tests/qwen35/check_report.zig new file mode 100644 index 00000000000..8137c561d60 --- /dev/null +++ b/zig/tests/qwen35/check_report.zig @@ -0,0 +1,33 @@ +//! The lines of a `check` run: one a check, PASS, FAIL or SKIP with its numbers, and the summary. + +const std = @import("std"); + +pub const Report = struct { + passed: usize = 0, + failed: usize = 0, + skipped: usize = 0, + + pub fn pass(r: *Report, name: []const u8, comptime fmt: []const u8, args: anytype) void { + r.passed += 1; + std.debug.print("PASS {s}: " ++ fmt ++ "\n", .{name} ++ args); + } + + pub fn fail(r: *Report, name: []const u8, comptime fmt: []const u8, args: anytype) void { + r.failed += 1; + std.debug.print("FAIL {s}: " ++ fmt ++ "\n", .{name} ++ args); + } + + pub fn skip(r: *Report, name: []const u8, why: []const u8) void { + r.skipped += 1; + std.debug.print("SKIP {s}: {s}\n", .{ name, why }); + } + + /// A check that stopped on an error instead of a verdict. + pub fn broke(r: *Report, name: []const u8, err: anyerror) void { + r.fail(name, "error.{s}", .{@errorName(err)}); + } + + pub fn summary(r: Report, seconds: f64) void { + std.debug.print("check {s}: {d} passed, {d} failed, {d} skipped in {d:.1} s\n", .{ if (r.failed == 0) "PASS" else "FAIL", r.passed, r.failed, r.skipped, seconds }); + } +}; diff --git a/zig/tests/qwen35/check_speed.zig b/zig/tests/qwen35/check_speed.zig new file mode 100644 index 00000000000..c4b3807b156 --- /dev/null +++ b/zig/tests/qwen35/check_speed.zig @@ -0,0 +1,66 @@ +//! The speed lines of `check`: cold prefill and decode with drafts off and on; they fail only when a run does. + +const std = @import("std"); +const check_ctx = @import("check_ctx.zig"); +const ids_file = @import("ids_file.zig"); +const lanes_session = @import("lanes_session.zig"); +const prefill_run = @import("prefill_run.zig"); + +const Ctx = check_ctx.Ctx; +const Session = lanes_session.Session; + +/// The longest prompt `run` times: the engine's capacity must hold it. +pub const longest_prefill = 8192; + +const prefill_lengths = [_]usize{ 13, 2048, longest_prefill }; + +pub fn run(c: *Ctx) void { + prefill(c); + for ([_]bool{ false, true }) |drafts| { + decode(c, drafts, c.short[0..1], 256); + decode(c, drafts, c.short, 128); + } +} + +fn prefill(c: *Ctx) void { + if (c.tp()) return c.report.skip("speed prefill", "a prompt pass runs on one rank"); + const prompt = ids_file.synthetic(c.arena, longest_prefill) catch |err| return c.report.broke("speed prefill", err); + for (prefill_lengths) |len| { + const name = std.fmt.allocPrint(c.arena, "speed prefill {d} tokens", .{len}) catch return; + const t = prefill_run.seconds(c.gpa, c.io, c.e, prompt[0..len]) catch |err| { + c.report.broke(name, err); + continue; + }; + c.report.pass(name, "{d:.3} s, {d:.0} tok/s", .{ t, @as(f64, @floatFromInt(len)) / t }); + } +} + +/// `prompts` generating `max_new` tokens each, the last of three runs (the first two capture the graphs). +fn decode(c: *Ctx, drafts: bool, prompts: []const ids_file.Prompt, max_new: u32) void { + const name = std.fmt.allocPrint(c.arena, "speed decode {d} stream{s}, drafts {s}", .{ prompts.len, if (prompts.len == 1) "" else "s", if (drafts) "on" else "off" }) catch return; + const job: Session.Job = .{ .prompts = prompts, .max_new = max_new, .drafts = drafts }; + for (0..2) |_| _ = c.session.run(c.arena, job) catch |err| return c.report.broke(name, err); + const done = c.session.run(c.arena, job) catch |err| return c.report.broke(name, err); + var rounds: u64 = 0; + for (done.replies) |r| rounds += r.rounds; + const n = done.tokens(); + const shared: f64 = @floatFromInt(@max(done.rounds, 1)); + c.report.pass(name, "{d:.1} tok/s, {d} tokens in {d:.3} s, {d:.2} tokens a stream round, {d:.1}% of {d} rounds replayed, {d:.0} us a round submitting, {d:.0} us a round in all (backend, a call: verify {d:.0} us, keep {d:.0} us, draft {d:.0} us)", .{ + @as(f64, @floatFromInt(n)) / done.seconds, + n, + done.seconds, + @as(f64, @floatFromInt(n)) / @as(f64, @floatFromInt(@max(rounds, 1))), + 100.0 * @as(f64, @floatFromInt(done.replayed)) / shared, + done.rounds, + @as(f64, @floatFromInt(done.submit_ns)) / shared / 1e3, + done.seconds * 1e6 / shared, + each(done, 0), + each(done, 1), + each(done, 2), + }); +} + +/// Microseconds a backend call of kind `which` (verify, keep, draft) took on average. +fn each(d: Session.Done, which: usize) f64 { + return @as(f64, @floatFromInt(d.spent[which])) / @as(f64, @floatFromInt(@max(d.calls[which], 1))) / 1e3; +} diff --git a/zig/tests/qwen35/draw_run.zig b/zig/tests/qwen35/draw_run.zig new file mode 100644 index 00000000000..184f6dc45cf --- /dev/null +++ b/zig/tests/qwen35/draw_run.zig @@ -0,0 +1,101 @@ +//! `draw`: the device argmax and top-k kernels against the host's (sample.zig) on tie-heavy rows (GPU). + +const std = @import("std"); +const hip = @import("hip"); +const qwen35 = @import("qwen3_5"); + +const sample = qwen35.sample; + +const Order = struct { + row: []const u16, + dtype: sample.Dtype, + + fn less(c: Order, a: u32, b: u32) bool { + const va = sample.widen(c.row, c.dtype, a); + const vb = sample.widen(c.row, c.dtype, b); + return va > vb or (va == vb and a < b); + } +}; + +pub fn run(gpa: std.mem.Allocator) !void { + var d = try hip.Runtime.open(); + defer d.close(); + var ctx = try hip.Context.init(&d, 0); + defer ctx.deinit(); + const caps = try hip.Device.kernelCaps(&d, 0); + var notes: hip.Policy.Notes = .{}; + var lib = try hip.Launcher.load(&d, (try hip.Policy.resolve("", .current, ¬es)).choices(), hip.kernels.images); + defer lib.unload(); + var stream = try hip.Stream.init(&d); + defer stream.deinit(); + var arena = try hip.Arena.init(&d, 1 << 20); + defer arena.deinit(); + const o: hip.ops.Ops = .{ .l = &lib, .bf16 = caps.act == .bf16, .stream = stream.handle, .arena = &arena }; + const dtype: sample.Dtype = if (caps.act == .f16) .f16 else .bf16; + const kind: hip.ops.Kind = if (caps.act == .f16) .f16 else .bf16; + var prng = std.Random.DefaultPrng.init(7); + const rnd = prng.random(); + const rows = 5; + for ([_]usize{ 1000, 4099, 248320 }) |vocab| { + // few distinct values (both zeros among them) so the k-th value is shared by many ids + const palette: [8]u16 = if (dtype == .f16) + .{ 0x0000, 0x8000, 0x3c00, 0xbc00, 0x4000, 0x4400, 0xc000, 0x3800 } + else + .{ 0x0000, 0x8000, 0x3f80, 0xbf80, 0x4000, 0x4080, 0xc000, 0x3f00 }; + const host = try gpa.alloc(u16, rows * vocab); + defer gpa.free(host); + for (host, 0..) |*v, i| v.* = if (i / vocab % 2 == 0) palette[rnd.uintLessThan(usize, palette.len)] else rnd.int(u16) & 0xbfff; + var logits = try hip.DeviceBuffer.alloc(&d, host.len * 2); + defer logits.free(); + try logits.upload(0, std.mem.sliceAsBytes(host)); + const ks = [rows]i32{ 1, 8, 28, 100, 0 }; + const stride = 100; + var ks_dev = try hip.DeviceBuffer.alloc(&d, rows * 4); + defer ks_dev.free(); + try ks_dev.upload(0, std.mem.sliceAsBytes(&ks)); + var arg_dev = try hip.DeviceBuffer.alloc(&d, rows * 4); + defer arg_dev.free(); + var ids_dev = try hip.DeviceBuffer.alloc(&d, rows * stride * 4); + defer ids_dev.free(); + var vals_dev = try hip.DeviceBuffer.alloc(&d, rows * stride * 2); + defer vals_dev.free(); + const t: hip.ops.Tensor = .{ .ptr = logits.base(), .kind = kind }; + try o.argmaxRows(t, rows, vocab, arg_dev.base()); + try o.topkRows(t, rows, vocab, ks_dev.base(), stride, ids_dev.base(), vals_dev.base()); + try stream.synchronize(); + var arg: [rows]i32 = undefined; + try arg_dev.download(0, std.mem.sliceAsBytes(&arg)); + const ids = try gpa.alloc(i32, rows * stride); + defer gpa.free(ids); + try ids_dev.download(0, std.mem.sliceAsBytes(ids)); + const vals = try gpa.alloc(u16, rows * stride); + defer gpa.free(vals); + try vals_dev.download(0, std.mem.sliceAsBytes(vals)); + for (0..rows) |r| { + const row = host[r * vocab ..][0..vocab]; + if (sample.argmax(row, dtype) != arg[r]) { + std.debug.print("argmax row {d} vocab {d}: device {d}, host {d}\n", .{ r, vocab, arg[r], sample.argmax(row, dtype) }); + return error.Mismatch; + } + const k: usize = @intCast(ks[r]); + if (k == 0) continue; + // the host's selection: sort every id by (value desc, id asc) and take k + const order = try gpa.alloc(u32, vocab); + defer gpa.free(order); + for (order, 0..) |*x, i| x.* = @intCast(i); + std.mem.sort(u32, order, Order{ .row = row, .dtype = dtype }, Order.less); + var want: std.AutoHashMapUnmanaged(u32, void) = .empty; + defer want.deinit(gpa); + for (order[0..k]) |id| try want.put(gpa, id, {}); + for (0..k) |j| { + const id: u32 = @intCast(ids[r * stride + j]); + if (!want.remove(id) or vals[r * stride + j] != row[id]) { + std.debug.print("top-{d} row {d} vocab {d}: id {d} is not the host's pick\n", .{ k, r, vocab, id }); + return error.Mismatch; + } + } + } + std.debug.print("vocab {d}: argmax and top-k of {d} rows equal the host's\n", .{ vocab, rows }); + } + std.debug.print("OK\n", .{}); +} diff --git a/zig/tests/qwen35/group.zig b/zig/tests/qwen35/group.zig new file mode 100644 index 00000000000..0b5d444f610 --- /dev/null +++ b/zig/tests/qwen35/group.zig @@ -0,0 +1,93 @@ +//! The tensor-parallel group of one test process: its options, and the group it joins through hip.joinGroup. + +const std = @import("std"); +const hip = @import("hip"); +const qwen35 = @import("qwen3_5"); + +/// One rank of `world`, joined at `master:port`; every rank runs the same command. +pub const Group = struct { + rank: usize = 0, + world: usize = 1, + master: []const u8 = "127.0.0.1", + port: u16 = 29551, + /// The policy flags, `key=value,...`. + policy: []const u8 = "", + + /// Takes the option at `args[i.*]` if it is one of the group's, moving `i` to its value. + pub fn option(g: *Group, args: []const [:0]const u8, i: *usize) !bool { + const name = args[i.*]; + const known = [_][]const u8{ "--tp", "--rank", "--master", "--port", "--policy" }; + const index = for (known, 0..) |k, n| { + if (std.mem.eql(u8, name, k)) break n; + } else return false; + i.* += 1; + if (i.* >= args.len) return error.MissingArgument; + const v = args[i.*]; + switch (index) { + 0 => g.world = try std.fmt.parseInt(usize, v, 10), + 1 => g.rank = try std.fmt.parseInt(usize, v, 10), + 2 => g.master = v, + 3 => g.port = try std.fmt.parseInt(u16, v, 10), + else => g.policy = v, + } + return true; + } + + /// What a group of more than one rank holds besides the engine: close it after the engine. + pub const Joined = struct { + gpa: std.mem.Allocator, + group: ?hip.collective.Group = null, + world: usize = 1, + /// What every rank runs under: rank 0's. + policy: hip.Policy = .{}, + + pub fn close(j: *Joined) void { + if (j.group) |g| g.close(j.gpa); + } + + /// The link to the other ranks (null: one rank). + pub fn link(j: *const Joined) ?hip.collective.Link { + return if (j.group) |g| g.link() else null; + } + }; + + /// Joins the other ranks (the group stays open until the engine is gone); one rank joins nothing. + pub fn join(g: Group, gpa: std.mem.Allocator, io: std.Io) !Joined { + const found = try resolve(g.policy, @intCast(g.rank)); + var j: Joined = .{ .gpa = gpa, .world = g.world, .policy = found.policy }; + if (g.world < 2) return j; + j.group = try hip.joinGroup(gpa, io, @intCast(g.rank), @intCast(g.world), g.master, g.port, found.caps, &j.policy); + return j; + } + + /// The engine on the device of this rank's number, with its share of the model. + pub fn engine(g: Group, gpa: std.mem.Allocator, io: std.Io, dir: []const u8, j: Joined, o: qwen35.engine.Options) !*qwen35.engine.Engine { + var own = o; + own.device = @intCast(g.rank); + own.rank = g.rank; + own.world = g.world; + own.group = j.group; + own.policy = j.policy; + return qwen35.engine.Engine.open(gpa, io, dir, own); + } +}; + +/// The policy of a test run on `device` and its caps: the GPU's defaults, `flags`, the variables and TF_POLICY, logged. +pub fn resolve(flags: []const u8, device: c_int) !struct { policy: hip.Policy, caps: hip.Caps } { + var d = try hip.Runtime.open(); + defer d.close(); + var ctx = try hip.Context.init(&d, device); + defer ctx.deinit(); + const caps = try hip.Device.kernelCaps(&d, device); + var notes: hip.Policy.Notes = .{}; + const policy = try hip.Policy.resolve(flags, .current, ¬es); + std.debug.print("policy {f} {s}\n", .{ policy, notes.text() }); + return .{ .policy = policy, .caps = caps }; +} + +/// A rank above 0 runs what rank 0 sends until it says stop. +pub fn follow(gpa: std.mem.Allocator, e: *qwen35.engine.Engine, j: *const Group.Joined) !void { + var w = try qwen35.worker.Worker.init(gpa, e); + defer w.deinit(); + return w.follow(j.link().?); +} diff --git a/zig/tests/qwen35/ids_file.zig b/zig/tests/qwen35/ids_file.zig new file mode 100644 index 00000000000..f856035953f --- /dev/null +++ b/zig/tests/qwen35/ids_file.zig @@ -0,0 +1,61 @@ +//! Token ids from a .npy file (int32 or int64), and the prompt sets the checks run. + +const std = @import("std"); +const npy = @import("npy"); + +/// The ids of `path`, owned by the caller. +pub fn load(gpa: std.mem.Allocator, io: std.Io, path: []const u8) ![]u32 { + const file = try std.Io.Dir.cwd().readFileAlloc(io, path, gpa, .limited(1 << 28)); + defer gpa.free(file); + const a = try npy.parse(file); + const ids = try gpa.alloc(u32, a.count()); + for (ids, 0..) |*t, i| t.* = if (std.mem.eql(u8, a.descr, " [--solo] [--no-drafts] [--resume PREFIX] [--tp N --rank R]` + +const std = @import("std"); +const lanes = @import("lanes"); +const qwen35 = @import("qwen3_5"); +const group_mod = @import("group.zig"); +const ids_file = @import("ids_file.zig"); +const lanes_session = @import("lanes_session.zig"); + +const Session = lanes_session.Session; + +pub fn run(gpa: std.mem.Allocator, io: std.Io, args: []const [:0]const u8) !void { + if (args.len < 3) return error.MissingArgument; + var arena_state = std.heap.ArenaAllocator.init(gpa); + defer arena_state.deinit(); + const arena = arena_state.allocator(); + const max_tokens = try std.fmt.parseInt(u32, args[2], 10); + var job: Session.Job = .{ .prompts = try ids_file.read(arena, io, args[1]), .max_new = max_tokens }; + var report: ?[]const u8 = null; + var resume_to: ?[]const u8 = null; + var group: group_mod.Group = .{}; + var i: usize = 3; + while (i < args.len) : (i += 1) { + if (try group.option(args, &i)) continue; + if (std.mem.eql(u8, args[i], "--resume")) { + i += 1; + resume_to = args[i]; + } else if (std.mem.eql(u8, args[i], "--solo")) job.solo = true else if (std.mem.eql(u8, args[i], "--no-drafts")) job.drafts = false else if (std.mem.eql(u8, args[i], "--report")) { + i += 1; + report = args[i]; + } else if (std.mem.eql(u8, args[i], "--seed")) { + i += 1; + job.sampling = .{ .seed = try std.fmt.parseInt(u64, args[i], 10), .temperature = if (job.sampling) |s| s.temperature else 1.0 }; + } else if (std.mem.eql(u8, args[i], "--temperature")) { + i += 1; + var s = job.sampling orelse lanes.Sampling{ .seed = 0 }; + s.temperature = try std.fmt.parseFloat(f64, args[i]); + job.sampling = s; + } else return error.UnknownOption; + } + var joined = try group.join(gpa, io); + defer joined.close(); + const e = try group.engine(gpa, io, args[0], joined, .{ .capacity = ids_file.longest(job.prompts) + 2 * max_tokens + 64, .prompt_rows = ids_file.longest(job.prompts) + 2 * max_tokens + 64, .streams = job.prompts.len, .batch_rows = @max(32, job.prompts.len * qwen35.hip_lanes.Hip.max_window) }); + defer e.deinit(); + if (group.rank > 0) return group_mod.follow(gpa, e, &joined); + var s: Session = undefined; + try s.init(gpa, io, e, joined.link()); + defer s.deinit(); + if (resume_to != null) s.h.keepPrompts(8, 1 << 30); + const done = try s.run(arena, job); + for (done.replies) |r| std.debug.print("{s}: {d} tokens, rounds {d}, accepted {d}\n", .{ r.name, r.tokens.len, r.rounds, r.accepted }); + std.debug.print("{s}: {d} streams, {d} tokens in {d:.3} s, {d:.1} tok/s\n", .{ if (job.solo) "solo" else "together", done.replies.len, done.tokens(), done.seconds, @as(f64, @floatFromInt(done.tokens())) / done.seconds }); + if (report) |path| try writeJson(gpa, io, path, try named(arena, done.replies)); + if (resume_to) |prefix| try again(gpa, io, &s, arena, prefix, job, done); +} + +fn writeJson(gpa: std.mem.Allocator, io: std.Io, path: []const u8, value: anytype) !void { + const json = try std.json.Stringify.valueAlloc(gpa, value, .{}); + defer gpa.free(json); + try std.Io.Dir.cwd().writeFile(io, .{ .sub_path = path, .data = json }); +} + +const Named = struct { name: []const u8, tokens: []const u32 }; +const Cached = struct { name: []const u8, cached: u32, tokens: []const u32 }; + +fn named(arena: std.mem.Allocator, rs: []const Session.Reply) ![]const Named { + const out = try arena.alloc(Named, rs.len); + for (out, rs) |*o, r| o.* = .{ .name = r.name, .tokens = r.tokens }; + return out; +} + +/// Each prompt again, extended by its reply and its own first tokens, one at a time on the kept caches. +fn again(gpa: std.mem.Allocator, io: std.Io, s: *Session, arena: std.mem.Allocator, prefix: []const u8, first: Session.Job, done: Session.Done) !void { + const extended = try lanes_session.extend(arena, first.prompts, done.replies); + var second = first; + second.prompts = extended; + second.solo = true; + const out = try s.run(arena, second); + const kept = try arena.alloc(Cached, out.replies.len); + const prompts = try arena.alloc(Named, extended.len); + for (kept, prompts, out.replies, extended) |*k, *n, r, p| { + std.debug.print("{s} again: {d} prompt tokens, {d} from the kept caches, {d} tokens\n", .{ r.name, p.ids.len, r.cached, r.tokens.len }); + k.* = .{ .name = r.name, .cached = r.cached, .tokens = r.tokens }; + n.* = .{ .name = p.name, .tokens = p.ids }; + } + try writeJson(gpa, io, try std.fmt.allocPrint(arena, "{s}-prompts.json", .{prefix}), prompts); + try writeJson(gpa, io, try std.fmt.allocPrint(arena, "{s}-replies.json", .{prefix}), kept); +} diff --git a/zig/tests/qwen35/lanes_session.zig b/zig/tests/qwen35/lanes_session.zig new file mode 100644 index 00000000000..c80e98f42bd --- /dev/null +++ b/zig/tests/qwen35/lanes_session.zig @@ -0,0 +1,118 @@ +//! Prompts through the lane core on one engine's HIP backend, as often as asked, each run's replies kept in memory. + +const std = @import("std"); +const hip = @import("hip"); +const lanes = @import("lanes"); +const qwen35 = @import("qwen3_5"); +const ids_file = @import("ids_file.zig"); + +const Hip = qwen35.hip_lanes.Hip; + +pub const Session = struct { + gpa: std.mem.Allocator, + io: std.Io, + e: *qwen35.engine.Engine, + h: *Hip, + cfg: lanes.Config, + clock: lanes.backend.WallClock, + + /// Rank 0 of a group of `link`'s ranks (null: a lone rank) runs the core; the others follow it. + pub fn init(s: *Session, gpa: std.mem.Allocator, io: std.Io, e: *qwen35.engine.Engine, link: ?hip.collective.Link) !void { + const h = try Hip.init(gpa, e); + errdefer h.deinit(); + if (link) |l| h.withLink(l); + if (link == null) h.measure(); + const rows = Hip.max_window; + s.* = .{ .gpa = gpa, .io = io, .e = e, .h = h, .cfg = try lanes.Config.init(gpa, h.facts(), rows, rows - 1), .clock = .{ .io = io } }; + } + + pub fn deinit(s: *Session) void { + s.cfg.deinit(s.gpa); + s.h.deinit(); + } + + pub const Job = struct { + prompts: []const ids_file.Prompt, + max_new: u32, + sampling: ?lanes.Sampling = null, + drafts: bool = true, + /// One stream at a time instead of all at once. + solo: bool = false, + }; + + pub const Reply = struct { name: []const u8, tokens: []const u32, rounds: u64, accepted: u64, cached: u32 }; + + pub const Done = struct { + replies: []const Reply, + seconds: f64, + /// Rounds run, rounds replayed from graphs and the host's nanoseconds submitting them, during the run. + rounds: u64, + replayed: u64, + submit_ns: u64, + /// Nanoseconds and calls of the backend's verifies, keeps and drafts. + spent: [3]u64, + calls: [3]u64, + + pub fn tokens(d: Done) usize { + var n: usize = 0; + for (d.replies) |r| n += r.tokens.len; + return n; + } + + pub fn accepted(d: Done) u64 { + var n: u64 = 0; + for (d.replies) |r| n += r.accepted; + return n; + } + }; + + /// The job's replies, in the arena, with no end token (replies run out at `max_new`). + pub fn run(s: *Session, arena: std.mem.Allocator, job: Job) !Done { + const streams = try s.gpa.alloc(lanes.Stream, job.prompts.len); + defer s.gpa.free(streams); + var made: usize = 0; + defer for (streams[0..made]) |*st| st.deinit(s.gpa); + for (streams, job.prompts) |*st, p| { + st.* = try lanes.Stream.init(s.gpa, .{ .id = p.name, .prompt = p.ids, .max_new = job.max_new, .sampling = job.sampling, .drafts = job.drafts, .history_len = @intCast(p.ids.len / 2), .shared_prefixes = p.shared }); + made += 1; + } + const replayed = s.e.graphs.replayed; + const rounds = s.e.graphs.rounds; + const submit = s.e.graphs.submit_ns; + const spent = s.h.spent; + const calls = s.h.calls; + const t0 = std.Io.Clock.awake.now(s.io); + if (job.solo) { + for (streams) |*st| try s.finish(&.{st}); + } else { + const all = try s.gpa.alloc(*lanes.Stream, streams.len); + defer s.gpa.free(all); + for (all, streams) |*a, *st| a.* = st; + try s.finish(all); + } + const seconds = @as(f64, @floatFromInt(std.Io.Clock.awake.now(s.io).toNanoseconds() - t0.toNanoseconds())) / 1e9; + const out = try arena.alloc(Reply, streams.len); + for (out, streams, job.prompts) |*r, *st, p| r.* = .{ .name = p.name, .tokens = try arena.dupe(u32, st.emitted()), .rounds = st.rounds, .accepted = st.accepted, .cached = st.cached }; + return .{ .replies = out, .seconds = seconds, .rounds = s.e.graphs.rounds - rounds, .replayed = s.e.graphs.replayed - replayed, .submit_ns = s.e.graphs.submit_ns - submit, .spent = delta(s.h.spent, spent), .calls = delta(s.h.calls, calls) }; + } + + fn finish(s: *Session, streams: []const *lanes.Stream) !void { + var engine = lanes.Engine.init(s.gpa, &s.cfg, s.h.backend(), s.clock.clock()); + defer engine.deinit(); + for (streams) |st| try engine.addStream(st); + while (engine.live.items.len > 0) try engine.step(); + } +}; + +fn delta(now: [3]u64, before: [3]u64) [3]u64 { + var out: [3]u64 = undefined; + for (&out, now, before) |*o, a, b| o.* = a - b; + return out; +} + +/// Each prompt extended by its reply and its own first tokens: what a next turn sends. +pub fn extend(arena: std.mem.Allocator, prompts: []const ids_file.Prompt, replies: []const Session.Reply) ![]const ids_file.Prompt { + const out = try arena.alloc(ids_file.Prompt, prompts.len); + for (out, prompts, replies) |*o, p, r| o.* = .{ .name = p.name, .ids = try std.mem.concat(arena, u32, &.{ p.ids, r.tokens, p.ids[0..@min(p.ids.len, 4)] }), .shared = p.shared }; + return out; +} diff --git a/zig/tests/qwen35/layers.zig b/zig/tests/qwen35/layers.zig new file mode 100644 index 00000000000..236a318704c --- /dev/null +++ b/zig/tests/qwen35/layers.zig @@ -0,0 +1,185 @@ +//! `layers [--tp N --rank R]`: the forward against qwen_rocm_dump.py's dump, byte for byte. + +const std = @import("std"); +const hip = @import("hip"); +const npy = @import("npy"); +const qwen35 = @import("qwen3_5"); + +const view = qwen35.view; +const Tensor = hip.ops.Tensor; + +const Gpu = struct { d: *const hip.Runtime, gpa: std.mem.Allocator, io: std.Io }; + +pub const Group = @import("group.zig").Group; + +/// One fixture file's data (the caller frees `bytes`). +fn read(g: Gpu, dir: []const u8, stem: []const u8, act: view.Kind) !struct { bytes: []u8, data: []const u8 } { + const name = try std.fmt.allocPrint(g.gpa, "{s}{s}", .{ stem, if (act == .bf16 and !std.mem.eql(u8, stem, "tokens") and !std.mem.eql(u8, stem, "sampled")) ".bf16.npy" else ".npy" }); + defer g.gpa.free(name); + const path = try std.fs.path.join(g.gpa, &.{ dir, name }); + defer g.gpa.free(path); + const bytes = try std.Io.Dir.cwd().readFileAlloc(g.io, path, g.gpa, .limited(1 << 31)); + return .{ .bytes = bytes, .data = (try npy.parse(bytes)).data }; +} + +fn download(g: Gpu, ptr: u64, n: usize) ![]u8 { + const out = try g.gpa.alloc(u8, n); + try hip.runtime.check(g.d.api.hipMemcpyDtoH(out.ptr, @ptrFromInt(ptr), n)); + return out; +} + +/// The first differing value of two activation rows' bytes, or null. +fn firstDiff(got: []const u8, want: []const u8) ?usize { + const i = std.mem.indexOfDiff(u8, got, want) orelse return null; + return i / 2; +} + +const Check = struct { + g: Gpu, + want: []const u8, // (layers, rows, hidden) of the step + hidden: usize, + stream: hip.Stream, + failed: ?usize = null, + + fn layer(ctx: *anyopaque, index: usize, x: Tensor, rows: usize) anyerror!void { + const c: *Check = @ptrCast(@alignCast(ctx)); + try c.stream.synchronize(); + const n = rows * c.hidden * 2; + const got = try download(c.g, x.ptr, n); + defer c.g.gpa.free(got); + if (c.failed == null) if (firstDiff(got, c.want[index * n ..][0..n])) |at| { + std.debug.print("FAIL layer {d}: residual differs first at row {d} column {d}\n", .{ index, at / c.hidden, at % c.hidden }); + c.failed = index; + }; + } +}; + +pub fn run(g: Gpu, model_dir: []const u8, dir: []const u8, group: Group) !void { + var ctx = try hip.Context.init(g.d, @intCast(group.rank)); + defer ctx.deinit(); + // the oracle's sums are the reference kernels': the fixtures pin them whatever the environment says + var notes: hip.Policy.Notes = .{}; + var policy = try hip.Policy.resolve("kernels=reference", .none, ¬es); + const caps = try hip.Device.kernelCaps(@constCast(g.d), @intCast(group.rank)); + // the group stays open to the end: its communicator is the forward's + const joined: ?hip.collective.Group = if (group.world > 1) try hip.joinGroup(g.gpa, g.io, @intCast(group.rank), @intCast(group.world), group.master, group.port, caps, &policy) else null; + defer if (joined) |j| j.close(g.gpa); + const comm: ?hip.collective.Comm = if (joined) |j| try j.open() else null; + var lib = try hip.Launcher.load(g.d, policy.choices(), hip.kernels.images); + defer lib.unload(); + const act: view.Kind = if (caps.act == .f16) .f16 else .bf16; + const dtype: qwen35.sample.Dtype = if (act == .f16) .f16 else .bf16; + var model = try qwen35.Model.loadRank(g.gpa, g.io, g.d, model_dir, if (group.world > 1) .{ .rank = group.rank, .world = group.world } else null); + defer model.deinit(); + const br = try qwen35.bridge.Bridge.init(g.gpa, g.d, &model, act); + defer br.deinit(); + br.model.tp = comm; + const m = &br.model; + const s = m.spec; + var stream = try hip.Stream.init(g.d); + defer stream.deinit(); + var arena = try hip.Arena.init(g.d, 2 << 30); + defer arena.deinit(); + const o: hip.ops.Ops = .{ .l = &lib, .bf16 = act == .bf16, .stream = stream.handle, .arena = &arena }; + + const tokens_f = try read(g, dir, "tokens", act); + defer g.gpa.free(tokens_f.bytes); + const sampled_f = try read(g, dir, "sampled", act); + defer g.gpa.free(sampled_f.bytes); + const tokens = std.mem.bytesAsSlice(i64, tokens_f.data); + const sampled = std.mem.bytesAsSlice(i64, sampled_f.data); + const len = tokens.len; + const positions = len + sampled.len + 1; + var pool = try qwen35.pages.Pool.init(g.gpa, g.d, m, qwen35.pages.pagesFor(positions) + 1, true); + defer pool.deinit(); + var caches = try qwen35.state.Caches.initFull(g.gpa, &pool, m, positions); + defer caches.deinit(g.gpa); + + const ids = try g.gpa.alloc(i32, len); + defer g.gpa.free(ids); + for (ids, tokens) |*i, t| i.* = @intCast(t); + var ids_dev = try hip.DeviceBuffer.fromHost(g.d, std.mem.sliceAsBytes(ids)); + defer ids_dev.free(); + + const want_layers = try read(g, dir, "prefill.layers", act); + defer g.gpa.free(want_layers.bytes); + var check: Check = .{ .g = g, .want = want_layers.data, .hidden = s.hidden, .stream = stream }; + const trace: qwen35.forward.Trace = .{ .ctx = &check, .layer = Check.layer }; + const hidden = try qwen35.forward.span(o, m, &caches, ids_dev.base(), len, 0, trace); + try stream.synchronize(); + if (check.failed) |l| return fail("prefill", l); + std.debug.print("PASS prefill: {d} rows, {d} layers' residuals equal\n", .{ len, s.n_layers }); + try compare(g, dir, "prefill.hidden", act, hidden.ptr, len * s.hidden * 2); + var token = try logitsToken(g, o, m, dir, "prefill.logits", act, dtype, hidden, len - 1); + try expectToken(token, sampled[0], "prefill"); + + // a decode step is a round of one row over a plan: the stream's slot, then the scratch slot + var plan_buf = try qwen35.plan.Buffer.init(g.d, 1, s.n_layers, pool.count); + defer plan_buf.deinit(); + var scratch = try qwen35.state.Caches.initFull(g.gpa, &pool, m, 1); + defer scratch.deinit(g.gpa); + const inputs = try g.gpa.alloc([2]u64, s.n_layers); + defer g.gpa.free(inputs); + for (0..sampled.len - 1) |step| { + arena.reset(); + try qwen35.window.kept(o, m, 1, inputs); + const pos = len + step; + const shape: qwen35.plan.Shape = .{ .rows = 1, .slots = 2, .span = @intCast(qwen35.plan.spanOf(pos + 1)) }; + const layout = qwen35.plan.Layout.of(1, 2, s.n_layers); + plan_buf.fill(layout, shape, &.{.{ .desc = caches.desc.base(), .pos = pos, .tokens = &.{token} }}, scratch.desc.base(), inputs); + try plan_buf.send(stream.handle, layout); + const round: qwen35.window.Round = .{ .plan = .{ .args = plan_buf.args(layout), .rows = 1, .slots = 2 }, .tokens = plan_buf.dev.base() + 4 * layout.tokens, .span = shape.span, .inputs = inputs }; + var name_buf: [32]u8 = undefined; + const stem = try std.fmt.bufPrint(&name_buf, "decode{d}", .{step}); + const want = try read(g, dir, try std.fmt.allocPrint(g.gpa, "{s}.layers", .{stem}), act); + defer g.gpa.free(want.bytes); + check = .{ .g = g, .want = want.data, .hidden = s.hidden, .stream = stream }; + const h = try qwen35.window.forward(o, m, round, trace); + try stream.synchronize(); + if (check.failed) |l| return fail(stem, l); + try compare(g, dir, try std.fmt.allocPrint(g.gpa, "{s}.hidden", .{stem}), act, h.ptr, s.hidden * 2); + token = try logitsToken(g, o, m, dir, try std.fmt.allocPrint(g.gpa, "{s}.logits", .{stem}), act, dtype, h, 0); + try expectToken(token, sampled[step + 1], stem); + std.debug.print("PASS {s}: residuals, final row, logits and token {d} equal\n", .{ stem, token }); + } +} + +fn fail(what: []const u8, layer: usize) error{Mismatch} { + std.debug.print("FAIL {s}: first differing layer {d}\n", .{ what, layer }); + return error.Mismatch; +} + +fn compare(g: Gpu, dir: []const u8, stem: []const u8, act: view.Kind, ptr: u64, n: usize) !void { + const want = try read(g, dir, stem, act); + defer g.gpa.free(want.bytes); + const got = try download(g, ptr, n); + defer g.gpa.free(got); + if (firstDiff(got, want.data)) |at| { + std.debug.print("FAIL {s}: differs first at value {d}\n", .{ stem, at }); + return error.Mismatch; + } +} + +/// The row's logits in the activation dtype (one-row projection, as the engine) compared, then its greedy token. +fn logitsToken(g: Gpu, o: hip.ops.Ops, m: *const view.Model, dir: []const u8, stem: []const u8, act: view.Kind, dtype: qwen35.sample.Dtype, hidden: Tensor, row: usize) !u32 { + const s = m.spec; + const x: Tensor = .{ .ptr = hidden.ptr + row * s.hidden * 2, .kind = act }; + var logits = try o.project(x, m.head, 1, false); + if (m.tp) |c| { + // one row: the ranks' slices in rank order are the vocabulary + const parts = try o.arena.take(c.world * m.head.n * 2); + try qwen35.reduce.gather(o, c, logits, parts, m.head.n); + logits.ptr = parts; + } + try hip.runtime.check(g.d.api.hipStreamSynchronize(o.stream)); + try compare(g, dir, stem, act, logits.ptr, s.vocab * 2); + const bytes = try download(g, logits.ptr, s.vocab * 2); + defer g.gpa.free(bytes); + return qwen35.sample.argmax(std.mem.bytesAsSlice(u16, @as([]align(2) u8, @alignCast(bytes))), dtype); +} + +fn expectToken(got: u32, want: i64, what: []const u8) !void { + if (got == want) return; + std.debug.print("FAIL {s}: token {d}, the engine drew {d}\n", .{ what, got, want }); + return error.Mismatch; +} diff --git a/zig/tests/qwen35/logit_kind.zig b/zig/tests/qwen35/logit_kind.zig new file mode 100644 index 00000000000..f0247855cfb --- /dev/null +++ b/zig/tests/qwen35/logit_kind.zig @@ -0,0 +1,36 @@ +//! The element types logits come in: the activation dtype the engine draws from, or fp32. + +const std = @import("std"); + +pub const Kind = enum { + bf16, + f16, + f32, + + pub fn size(k: Kind) usize { + return if (k == .f32) 4 else 2; + } + + pub fn descr(k: Kind) []const u8 { + return switch (k) { + .bf16 => " " " @as(f32, @bitCast(@as(u32, std.mem.readInt(u16, bytes[0..2], .little)) << 16)), + .f16 => @as(f16, @bitCast(std.mem.readInt(u16, bytes[0..2], .little))), + .f32 => @as(f32, @bitCast(std.mem.readInt(u32, bytes[0..4], .little))), + }; + } +}; + +test "elements decode to their values" { + try std.testing.expectEqual(@as(f64, 1.0), Kind.bf16.at(&.{ 0x80, 0x3f })); + try std.testing.expectEqual(@as(f64, 1.0), Kind.f16.at(&.{ 0x00, 0x3c })); + try std.testing.expectEqual(@as(f64, -2.0), Kind.f32.at(&.{ 0x00, 0x00, 0x00, 0xc0 })); +} diff --git a/zig/tests/qwen35/logits_run.zig b/zig/tests/qwen35/logits_run.zig new file mode 100644 index 00000000000..61ac1c10870 --- /dev/null +++ b/zig/tests/qwen35/logits_run.zig @@ -0,0 +1,120 @@ +//! `logits [--f32] [--decode]`: every row's logits for tools/truth/score.py to score. + +const std = @import("std"); +const hip = @import("hip"); +const qwen35 = @import("qwen3_5"); +const ids_file = @import("ids_file.zig"); +const Kind = @import("logit_kind.zig").Kind; + +const Engine = qwen35.engine.Engine; + +/// Rows a head projection covers at once. +pub const chunk = 32; + +pub const Mode = struct { decode: bool = false, wide: bool = false }; + +/// Takes each block of rows as it is read: rows `first..first + count` of `vocab` logits, `bytes` in the kind's layout. +pub const Sink = struct { + ctx: *anyopaque, + put: *const fn (ctx: *anyopaque, first: usize, count: usize, bytes: []const u8) anyerror!void, +}; + +/// The head's width in logits (the padded vocabulary). +pub fn vocab(e: *const Engine) usize { + return e.model().spec.vocab; +} + +pub fn kindOf(e: *const Engine, mode: Mode) Kind { + return if (mode.wide) .f32 else if (e.model().act == .f16) .f16 else .bf16; +} + +/// Every row's logits of `ids` into `sink`, in blocks of up to `chunk` rows. +pub fn stream(gpa: std.mem.Allocator, e: *Engine, ids: []const u32, mode: Mode, sink: Sink) !void { + const m = e.model(); + var caches = try e.newCaches(ids.len + 8); + defer { + e.drain(); + caches.deinit(gpa); + } + e.prompts.reset(); + const o: hip.ops.Ops = e.ops(&e.prompts); + var ids_dev = try hip.DeviceBuffer.fromHost(&e.driver, std.mem.sliceAsBytes(ids)); + defer ids_dev.free(); + const hidden = try qwen35.forward.span(o, m, &caches, ids_dev.base(), if (mode.decode) 1 else ids.len, 0, null); + + const width = vocab(e) * kindOf(e, mode).size(); + const block = try gpa.alloc(u8, chunk * width); + defer gpa.free(block); + if (mode.decode) { + // row 0 from its one-row prefill, then each token a one-row round at its slot, kept before the next + const first = try o.project(hidden, m.head, 1, mode.wide); + try e.stream.synchronize(); + try hip.runtime.check(e.driver.api.hipMemcpyDtoH(block.ptr, @ptrFromInt(first.ptr), width)); + for (1..ids.len) |i| { + const rows = [1]Engine.Rows{.{ .caches = &caches, .pos = i, .tokens = ids[i..][0..1] }}; + const reqs = [1]qwen35.draw.Request{.{ .sampling = null, .position = i + 1 }}; + var drawn: [1]u32 = undefined; + const r = try e.verify(&rows, &reqs, &drawn); + const round: hip.ops.Ops = e.ops(&e.rounds); + const logits = try round.project(r.hidden, m.head, 1, mode.wide); + try e.stream.synchronize(); + try hip.runtime.check(e.driver.api.hipMemcpyDtoH(block[(i % chunk) * width ..].ptr, @ptrFromInt(logits.ptr), width)); + e.keep(0, 1); + try e.flush(); + if (i % chunk == chunk - 1) try sink.put(sink.ctx, i + 1 - chunk, chunk, block); + } + const tail = ids.len % chunk; + if (tail > 0) try sink.put(sink.ctx, ids.len - tail, tail, block[0 .. tail * width]); + return; + } + var row: usize = 0; + while (row < ids.len) : (row += chunk) { + const rows = @min(chunk, ids.len - row); + const at = e.prompts.mark(); + const logits = try o.project(qwen35.forward.at(hidden, row * m.spec.hidden), m.head, rows, mode.wide); + try e.stream.synchronize(); + try hip.runtime.check(e.driver.api.hipMemcpyDtoH(block.ptr, @ptrFromInt(logits.ptr), rows * width)); + e.prompts.release(at); + try sink.put(sink.ctx, row, rows, block[0 .. rows * width]); + } +} + +/// The rows of a whole file in memory, written as a .npy at the end. +const File = struct { + body: []u8, + width: usize, + + fn put(ctx: *anyopaque, first: usize, _: usize, bytes: []const u8) anyerror!void { + const f: *File = @ptrCast(@alignCast(ctx)); + @memcpy(f.body[first * f.width ..][0..bytes.len], bytes); + } +}; + +pub fn run(gpa: std.mem.Allocator, io: std.Io, args: []const [:0]const u8) !void { + if (args.len < 3) return error.MissingArgument; + var mode: Mode = .{}; + for (args[3..]) |a| { + if (std.mem.eql(u8, a, "--f32")) mode.wide = true else if (std.mem.eql(u8, a, "--decode")) mode.decode = true else return error.UnknownOption; + } + const ids = try ids_file.load(gpa, io, args[1]); + defer gpa.free(ids); + const e = try Engine.open(gpa, io, args[0], .{ .capacity = ids.len + 64, .prompt_rows = ids.len + 64, .streams = 1, .batch_rows = 32, .policy = (try @import("group.zig").resolve("", 0)).policy }); + defer e.deinit(); + const kind = kindOf(e, mode); + var header_buf: [128]u8 = undefined; + const dict = try std.fmt.bufPrint(&header_buf, "{{'descr': '{s}', 'fortran_order': False, 'shape': ({d}, {d}), }}", .{ kind.descr(), ids.len, vocab(e) }); + const pad = 64 - (10 + dict.len + 1) % 64; + const head = 10 + dict.len + pad + 1; + const width = vocab(e) * kind.size(); + const out = try gpa.alloc(u8, head + ids.len * width); + defer gpa.free(out); + @memcpy(out[0..8], "\x93NUMPY\x01\x00"); + std.mem.writeInt(u16, out[8..10], @intCast(dict.len + pad + 1), .little); + @memcpy(out[10..][0..dict.len], dict); + @memset(out[10 + dict.len ..][0..pad], ' '); + out[head - 1] = '\n'; + var file: File = .{ .body = out[head..], .width = width }; + try stream(gpa, e, ids, mode, .{ .ctx = &file, .put = File.put }); + try std.Io.Dir.cwd().writeFile(io, .{ .sub_path = args[2], .data = out }); + std.debug.print("wrote {d}{s} rows x {d} logits to {s}\n", .{ ids.len, if (mode.decode) " decoded" else "", vocab(e), args[2] }); +} diff --git a/zig/tests/qwen35/main.zig b/zig/tests/qwen35/main.zig new file mode 100644 index 00000000000..bf894c963ce --- /dev/null +++ b/zig/tests/qwen35/main.zig @@ -0,0 +1,195 @@ +//! Qwen3.5 / 3.6 model tests: `tf-qwen35-test ...`, the commands listed in `usage`. + +const std = @import("std"); +const hip = @import("hip"); +const qwen35 = @import("qwen3_5"); + +const Buf = qwen35.weights.Buf; +const Tensor = qwen35.table.Tensor; + +/// No per-thread alternate signal stack: its thread-local leaves RCCL's and HIP's threads too little stack to start. +pub const std_options: std.Options = .{ .signal_stack_size = null }; + +const usage = "usage: tf-qwen35-test check [--tp N --rank R --master H --port P] [--prompts FILE] [--truth T --ids IDS] [--speed] [--only invariants|accuracy|speed] | upload [first layers] | digest [--tp N --rank R] | layers [--tp N --rank R [--master HOST] [--port P]] | lanes ... | prefill ... | logits [--f32] [--decode] | rows [n] | draw x\n"; + +/// The subcommands that take their arguments after the name. +const commands = [_]struct { name: []const u8, run: *const fn (std.mem.Allocator, std.Io, []const [:0]const u8) anyerror!void }{ + .{ .name = "rows", .run = @import("rows_run.zig").run }, + .{ .name = "logits", .run = @import("logits_run.zig").run }, + .{ .name = "prefill", .run = @import("prefill_run.zig").run }, + .{ .name = "lanes", .run = @import("lanes_run.zig").run }, +}; + +pub fn main(init: std.process.Init) !u8 { + const args = try init.minimal.args.toSlice(init.arena.allocator()); + if (args.len < 3) { + std.debug.print(usage, .{}); + return 2; + } + if (std.mem.eql(u8, args[1], "digest")) { + var rank: ?qwen35.slicing.Rank = null; + if (args.len > 6 and std.mem.eql(u8, args[3], "--tp")) rank = .{ .world = try std.fmt.parseInt(usize, args[4], 10), .rank = try std.fmt.parseInt(usize, args[6], 10) }; + digest(init.gpa, init.io, args[2], rank) catch |e| { + std.debug.print("FAIL {t}\n", .{e}); + return 1; + }; + return 0; + } + if (std.mem.eql(u8, args[1], "draw")) { + @import("draw_run.zig").run(init.gpa) catch |e| { + std.debug.print("FAIL {t}\n", .{e}); + return 1; + }; + return 0; + } + for (commands) |c| if (std.mem.eql(u8, args[1], c.name)) { + c.run(init.gpa, init.io, args[2..]) catch |e| { + std.debug.print("FAIL {t}\n", .{e}); + return 1; + }; + return 0; + }; + if (std.mem.eql(u8, args[1], "layers") and args.len > 3) { + var d = try hip.Runtime.open(); + defer d.close(); + var group: @import("group.zig").Group = .{}; + var i: usize = 4; + while (i < args.len) : (i += 1) if (!try group.option(args, &i)) return 2; + @import("layers.zig").run(.{ .d = &d, .gpa = init.gpa, .io = init.io }, args[2], args[3], group) catch |e| { + std.debug.print("FAIL {t}\n", .{e}); + return 1; + }; + return 0; + } + if (std.mem.eql(u8, args[1], "check")) return @import("check.zig").run(init.gpa, init.io, args[2..]) catch |e| { + std.debug.print("FAIL {t}\n", .{e}); + return 1; + }; + if (!std.mem.eql(u8, args[1], "upload")) { + std.debug.print(usage, .{}); + return 2; + } + var driver = try hip.Runtime.open(); + defer driver.close(); + var ctx = try hip.Context.init(&driver, 0); + defer ctx.deinit(); + const limit = if (args.len > 3) try std.fmt.parseInt(usize, args[3], 10) else std.math.maxInt(usize); + run(init.gpa, init.io, &driver, args[2], limit) catch |e| { + std.debug.print("FAIL {t}\n", .{e}); + return 1; + }; + return 0; +} + +/// One line per host tensor: its path, dtype, shape and the SHA-256 of its bytes. +fn line(path: []const u8, t: Tensor) void { + var sum: [32]u8 = undefined; + std.crypto.hash.sha2.Sha256.hash(t.bytes, &sum, .{}); + std.debug.print("{s} {t} {any} {s}\n", .{ path, t.dtype, t.shape[0..t.rank], std.fmt.bytesToHex(sum, .lower) }); +} + +fn emit(gpa: std.mem.Allocator, path: []const u8, v: anytype) !void { + const T = @TypeOf(v); + switch (@typeInfo(T)) { + .@"struct" => if (T == Tensor) line(path, v) else inline for (@typeInfo(T).@"struct".field_names) |name| { + if (comptime std.mem.eql(u8, name, "arena") or std.mem.eql(u8, name, "owned") or std.mem.eql(u8, name, "io")) continue; + const sub = try std.fmt.allocPrint(gpa, "{s}.{s}", .{ path, name }); + defer gpa.free(sub); + try emit(gpa, sub, @field(v, name)); + }, + .@"union" => switch (v) { + inline else => |payload, tag| { + const sub = try std.fmt.allocPrint(gpa, "{s}.{s}", .{ path, @tagName(tag) }); + defer gpa.free(sub); + try emit(gpa, sub, payload); + }, + }, + .optional => if (v) |x| try emit(gpa, path, x), + .int, .bool => std.debug.print("{s} {any}\n", .{ path, v }), + else => {}, + } +} + +fn digest(gpa: std.mem.Allocator, io: std.Io, dir: []const u8, rank: ?qwen35.slicing.Rank) !void { + var ck = try qwen35.Checkpoint.open(gpa, io, dir); + defer ck.close(); + var scratch: std.heap.ArenaAllocator = .init(gpa); + defer scratch.deinit(); + const embed = try ck.embed(scratch.allocator()); + try emit(gpa, "embed", embed); + try emit(gpa, "final_norm", try ck.finalNorm(scratch.allocator())); + const head = try ck.head(scratch.allocator()); + if (rank) |r| { + try emit(gpa, "head", try qwen35.slicing.vocabRows(scratch.allocator(), head orelse embed, ck.spec().vocab, r)); + } else try emit(gpa, "head", head); + for (0..ck.spec().n_layers) |i| { + var layer = try ck.layer(i); + defer layer.deinit(); + if (rank) |r| try qwen35.slicing.layer(&layer, ck.spec(), r); + const path = try std.fmt.allocPrint(gpa, "L{d}", .{i}); + defer gpa.free(path); + try emit(gpa, path, layer.body); + } + var mtp = try ck.mtp(); + defer if (mtp) |*m| m.deinit(); + if (rank) |r| if (mtp) |*m| if (m.head) |p| { + m.head = try qwen35.slicing.vocabRows(m.arena.allocator(), p, ck.spec().vocab, r); + }; + try emit(gpa, "mtp", mtp); +} + +const Check = struct { + gpa: std.mem.Allocator, + driver: *const hip.Runtime, + buffers: usize = 0, + bytes: usize = 0, + + /// Reads `b` back and compares dtype, shape and bytes with the host tensor. + fn buf(c: *Check, b: Buf, t: Tensor) !void { + if (b.dtype != t.dtype or b.rank != t.rank or !std.mem.eql(u8, std.mem.sliceAsBytes(&b.shape), std.mem.sliceAsBytes(&t.shape)) or b.len != t.bytes.len) return error.ShapeMismatch; + const got = try c.gpa.alloc(u8, b.len); + defer c.gpa.free(got); + const device: hip.DeviceBuffer = .{ .r = c.driver, .ptr = @ptrFromInt(b.ptr), .len = b.len }; + try device.download(0, got); + if (!std.mem.eql(u8, got, t.bytes)) return error.BytesDiffer; + c.buffers += 1; + c.bytes += b.len; + } + + /// Walks a device struct and its host twin (same field and tag names) and checks every buffer. + fn walk(c: *Check, dev: anytype, h: anytype) !void { + const T = @TypeOf(dev); + switch (@typeInfo(T)) { + .@"struct" => if (T == Buf) try c.buf(dev, h) else inline for (@typeInfo(T).@"struct".field_names) |name| try c.walk(@field(dev, name), if (@hasField(@TypeOf(h), name)) @field(h, name) else {}), + .@"union" => switch (dev) { + inline else => |payload, tag| try c.walk(payload, @field(h, @tagName(tag))), + }, + .optional => if (dev) |d| try c.walk(d, h.?) else if (h != null) return error.ShapeMismatch, + else => {}, + } + } +}; + +fn run(gpa: std.mem.Allocator, io: std.Io, driver: *const hip.Runtime, dir: []const u8, limit: usize) !void { + var ck = try qwen35.Checkpoint.open(gpa, io, dir); + defer ck.close(); + var model = try qwen35.Model.fromCheckpoint(gpa, driver, &ck, limit); + defer model.deinit(); + var c: Check = .{ .gpa = gpa, .driver = driver }; + var scratch: std.heap.ArenaAllocator = .init(gpa); + defer scratch.deinit(); + try c.walk(model.embed, (try ck.embed(scratch.allocator()))); + try c.walk(model.final_norm, try ck.finalNorm(scratch.allocator())); + try c.walk(model.head, try ck.head(scratch.allocator())); + for (model.layers, 0..) |layer, i| { + var host_layer = try ck.layer(i); + defer host_layer.deinit(); + try c.walk(layer, host_layer.body); + } + if (model.layers.len == ck.spec().n_layers) { + var host_mtp = try ck.mtp(); + defer if (host_mtp) |*m| m.deinit(); + try c.walk(model.mtp, host_mtp); + } + std.debug.print("PASS {d} layers, {d} buffers, {d} MiB read back equal to the host index\n", .{ model.layers.len, c.buffers, c.bytes >> 20 }); +} diff --git a/zig/tests/qwen35/matrix.sh b/zig/tests/qwen35/matrix.sh new file mode 100644 index 00000000000..06a4d5b1d0d --- /dev/null +++ b/zig/tests/qwen35/matrix.sh @@ -0,0 +1,125 @@ +#!/bin/sh +# usage: matrix.sh [options] MODELS_DIR DEVICES... [-- CHECK_ARGS]: a markdown table of `check` per model and setting. + +# DEVICES: an argument a group, a comma list of HIP ordinals ("6,7" is tensor parallel over two); exit 1 on any FAIL. + +bin=zig-out/bin/tf-qwen35-test +log= +port=29551 +limit=3000 +speed= +ids= +models= +truths= +envs= +extra= + +die() { echo "matrix.sh: $*" >&2; exit 2; } +value() { [ "$1" -ge 2 ] || die "$2 needs a value"; } + +while [ $# -gt 0 ]; do + case $1 in + --model) value $# "$1"; models="$models $2"; shift 2 ;; # a directory under MODELS_DIR; default: all of them + --env) value $# "$1"; envs="$envs $2"; shift 2 ;; # VAR=V1,V2; every combination is run + --truth) value $# "$1"; truths="$truths $2"; shift 2 ;; # NAME=FILE, the fp64 truth .npy model NAME is scored against + --ids) value $# "$1"; ids=$2; shift 2 ;; # the ids .npy the long prompts and the truth rows are cut from + --speed) speed=--speed; shift ;; + --bin) value $# "$1"; bin=$2; shift 2 ;; + --log) value $# "$1"; log=$2; shift 2 ;; + --port) value $# "$1"; port=$2; shift 2 ;; + --timeout) value $# "$1"; limit=$2; shift 2 ;; + -*) die "unknown option $1" ;; + *) break ;; + esac +done +[ $# -ge 2 ] || die "usage: matrix.sh [options] MODELS_DIR DEVICES... [-- CHECK_ARGS]" +dir=$1 +shift +groups= +while [ $# -gt 0 ] && [ "$1" != -- ]; do groups="$groups $1"; shift; done +[ $# -gt 0 ] && shift && extra="$*" # after `--`, arguments for every `check` as they are +[ -n "$groups" ] || die "no DEVICES" +[ -d "$dir" ] || die "$dir is not a directory" +[ -x "$bin" ] || die "$bin is not built" +if [ -z "$models" ]; then + for d in "$dir"/[!.]*/; do models="$models $(basename "$d")"; done +fi +[ -n "$log" ] || log=$(mktemp -d) +mkdir -p "$log" + +# every combination of the --env settings, a line each ("VAR=a OTHER=x"); one empty line when there are none +combos() ( + prefix=$1 + shift + if [ $# -eq 0 ]; then echo "$prefix"; return; fi + spec=$1 + shift + for v in $(echo "${spec#*=}" | tr ',' ' '); do combos "$prefix ${spec%%=*}=$v" "$@"; done +) + +truth_of() { + for t in $truths; do + [ "${t%%=*}" = "$1" ] && { echo "${t#*=}"; return; } + done +} + +# the numbers of one run's lines, as the cells of its table row +summarize() { + awk ' + function num(re, s) { if (match($0, re)) { s = substr($0, RSTART, RLENGTH); sub(/^[^=:]*[=:] */, "", s); sub(/[% ].*$/, "", s); return s } return "-" } + /^(PASS|FAIL) (rows|lanes) / { total++; if ($1 == "PASS") ok++ } + /^(PASS|FAIL) accuracy prefill/ { klp = num("KL mean=[^ ]+"); top = num("top1=[^ ]+") } + /^(PASS|FAIL) accuracy decode/ { kld = num("KL mean=[^ ]+") } + /^PASS speed prefill 2048 / { pf2 = num("[0-9]+ tok/s") } + /^PASS speed prefill 8192 / { pf8 = num("[0-9]+ tok/s") } + /^PASS speed decode 1 stream, drafts off/ { d1 = num(": [0-9.]+ tok/s") } + /^PASS speed decode 1 stream, drafts on/ { d1m = num(": [0-9.]+ tok/s") } + /^PASS speed decode 4 streams, drafts off/ { d4 = num(": [0-9.]+ tok/s") } + /^PASS speed decode 4 streams, drafts on/ { d4m = num(": [0-9.]+ tok/s") } + END { + if (!klp) klp = "-"; if (!kld) kld = "-"; if (!top) top = "-" + if (!pf2) pf2 = "-"; if (!pf8) pf8 = "-"; if (!d1) d1 = "-"; if (!d1m) d1m = "-"; if (!d4) d4 = "-"; if (!d4m) d4m = "-" + printf "%d/%d|%s|%s|%s|%s|%s|%s|%s|%s|%s", ok, total, klp, kld, top, pf2, pf8, d1, d1m, d4, d4m + }' "$1" +} + +rows=$log/rows.txt +: > "$rows" +bad=0 +n=0 +for model in $models; do + [ -d "$dir/$model" ] || die "$dir/$model is not a model directory" + truth=$(truth_of "$model") + for devs in $groups; do + tp=$(echo "$devs" | awk -F, '{print NF}') + combos "" $envs > "$log/settings.txt" + while IFS= read -r setting; do + setting=$(echo $setting) + n=$((n + 1)) + out=$log/run$n.log + args="$dir/$model --tp $tp --port $((port + n - 1))" + [ -n "$ids" ] && args="$args --ids $ids" + [ -n "$truth" ] && args="$args --truth $truth" + args="$args $speed $extra" + r=1 + while [ "$r" -lt "$tp" ]; do + # shellcheck disable=SC2086 + env -u ROCR_VISIBLE_DEVICES HIP_VISIBLE_DEVICES=$devs $setting timeout -s KILL "$limit" "$bin" check $args --rank $r > "$log/run$n.rank$r.log" 2>&1 & + r=$((r + 1)) + done + # shellcheck disable=SC2086 + env -u ROCR_VISIBLE_DEVICES HIP_VISIBLE_DEVICES=$devs $setting timeout -s KILL "$limit" "$bin" check $args --rank 0 > "$out" 2>&1 + code=$? + wait + status=PASS + if [ "$code" -ne 0 ] || [ "$(grep -c '^FAIL ' "$out")" -ne 0 ] || ! grep -q '^check PASS' "$out"; then status=FAIL; bad=1; fi + echo "$model|$devs|$tp|${setting:--}|$status|$(summarize "$out")" >> "$rows" + echo "run $n: $model on $devs ${setting:+($setting) }$status, $out" >&2 + done < "$log/settings.txt" + done +done + +echo "| model | devices | tp | env | status | invariants | KL prefill | KL decode | top-1 % | prefill 2048 tok/s | prefill 8192 tok/s | decode 1 | decode 1 + drafts | decode 4 | decode 4 + drafts |" +echo "|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|" +sed 's/|/ | /g; s/^/| /; s/$/ |/' "$rows" +exit $bad diff --git a/zig/tests/qwen35/prefill_run.zig b/zig/tests/qwen35/prefill_run.zig new file mode 100644 index 00000000000..447cfdac776 --- /dev/null +++ b/zig/tests/qwen35/prefill_run.zig @@ -0,0 +1,38 @@ +//! `prefill ...`: cold synthetic prompts of each length through prefill, as prompt tokens a second. + +const std = @import("std"); +const qwen35 = @import("qwen3_5"); +const ids_file = @import("ids_file.zig"); + +/// The median seconds of three cold prefills of `prompt` after one warm-up. +pub fn seconds(gpa: std.mem.Allocator, io: std.Io, e: *qwen35.engine.Engine, prompt: []const u32) !f64 { + var times: [3]f64 = undefined; + for (0..4) |rep| { + var caches = try e.newCaches(prompt.len + 8); + defer { + e.drain(); + caches.deinit(gpa); + } + const t0 = std.Io.Clock.awake.now(io); + _ = try e.prefill(&caches, prompt, 0, null, .{ .sampling = null, .position = prompt.len }, null); + const dt = @as(f64, @floatFromInt(std.Io.Clock.awake.now(io).toNanoseconds() - t0.toNanoseconds())) / 1e9; + if (rep > 0) times[rep - 1] = dt; + } + std.mem.sort(f64, ×, {}, std.sort.asc(f64)); + return times[1]; +} + +pub fn run(gpa: std.mem.Allocator, io: std.Io, args: []const [:0]const u8) !void { + if (args.len < 2) return error.MissingArgument; + var longest: usize = 0; + for (args[1..]) |a| longest = @max(longest, try std.fmt.parseInt(usize, a, 10)); + const e = try qwen35.engine.Engine.open(gpa, io, args[0], .{ .capacity = longest + 64, .prompt_rows = longest + 64, .streams = 1, .batch_rows = 32, .policy = (try @import("group.zig").resolve("", 0)).policy }); + defer e.deinit(); + const prompt = try ids_file.synthetic(gpa, longest); + defer gpa.free(prompt); + for (args[1..]) |a| { + const len = try std.fmt.parseInt(usize, a, 10); + const t = try seconds(gpa, io, e, prompt[0..len]); + std.debug.print("RESULT prefill {d} tokens: {d:.3} s, {d:.0} tok/s\n", .{ len, t, @as(f64, @floatFromInt(len)) / t }); + } +} diff --git a/zig/tests/qwen35/prompts.json b/zig/tests/qwen35/prompts.json new file mode 100644 index 00000000000..34e48d1a549 --- /dev/null +++ b/zig/tests/qwen35/prompts.json @@ -0,0 +1 @@ +{"a": [9707, 11, 1879, 0, 358, 1079, 264, 1273, 2814, 311, 1490, 1045, 1128, 13, 3555, 498, 3170, 1431, 30, 576, 6722, 315, 9625, 374], "b": [785, 6722, 315, 9625, 374, 12095, 13, 576, 3974, 15217, 21893, 39380, 916], "c": [151644, 872, 198, 5501, 3270, 264, 2805, 32794, 911, 279, 17951, 13, 151645, 198, 151644, 77091, 198], "d": [16, 11, 220, 17, 11, 220, 18, 11, 220, 19, 11, 220, 20]} \ No newline at end of file diff --git a/zig/tests/qwen35/rows_run.zig b/zig/tests/qwen35/rows_run.zig new file mode 100644 index 00000000000..ea60d0ac67d --- /dev/null +++ b/zig/tests/qwen35/rows_run.zig @@ -0,0 +1,153 @@ +//! `rows [n] [streams] [keep]`: the window invariant layer by layer, naming the first difference. + +const std = @import("std"); +const hip = @import("hip"); +const qwen35 = @import("qwen3_5"); +const ids_file = @import("ids_file.zig"); + +const Engine = qwen35.engine.Engine; + +/// Every layer's residual rows of one run: (layers + 1, n, hidden) bytes, the last slot the final rows. +const Sink = struct { + e: *Engine, + bytes: []u8, + n: usize, + /// The row the next capture lands at, and the real rows of the round (the forward may run padding rows past them). + row: usize = 0, + take: usize = 0, + + fn width(s: *const Sink) usize { + return s.e.model().spec.hidden * s.e.model().act.size(); + } + + fn put(s: *Sink, slot: usize, x: hip.ops.Tensor, rows: usize) !void { + try s.e.stream.synchronize(); + const w = s.width(); + const at = (slot * s.n + s.row) * w; + try hip.runtime.check(s.e.driver.api.hipMemcpyDtoH(s.bytes[at..].ptr, @ptrFromInt(x.ptr), rows * w)); + } + + fn layer(ctx: *anyopaque, index: usize, x: hip.ops.Tensor, rows: usize) anyerror!void { + const s: *Sink = @ptrCast(@alignCast(ctx)); + _ = rows; + try s.put(index, x, s.take); + } +}; + +/// One round of every stream's `tokens` from `pos[j]` of `caches[j]`, in at least `pad` rows, captured into `sink`. +fn round(e: *Engine, caches: []const *qwen35.state.Caches, pos: []const usize, tokens: []const []const u32, keep: usize, sink: *Sink, pad: usize) !void { + var rows: [8]Engine.Rows = undefined; + var reqs: [128]qwen35.draw.Request = undefined; + var out: [128]u32 = undefined; + var total: usize = 0; + for (caches, pos, tokens, 0..) |c, p, t, j| { + rows[j] = .{ .caches = c, .pos = p, .tokens = t }; + for (0..t.len) |i| reqs[total + i] = .{ .sampling = null, .position = p + i + 1 }; + total += t.len; + } + sink.take = total; + e.round.trace = .{ .ctx = sink, .layer = Sink.layer }; + e.round.pad_to = pad; + defer { + e.round.trace = null; + e.round.pad_to = 0; + } + const done = try e.verify(rows[0..caches.len], reqs[0..total], out[0..total]); + try sink.put(e.model().spec.n_layers, done.hidden, total); + for (tokens, 0..) |t, j| e.keep(j, @min(keep, t.len)); + try e.flush(); + try e.stream.synchronize(); +} + +/// Streams of `n` rows each, the first `keep` of each kept. +pub const Case = struct { streams: usize, n: usize, keep: usize, pad: usize = 0 }; + +/// Where a case's two runs first differ. +pub const Diff = struct { layer: usize, kind: []const u8, stream: usize, row: usize, column: usize }; + +/// Runs one case over prompts cut from `ids`; null when every layer's rows and the final rows are equal. +pub fn runCase(gpa: std.mem.Allocator, e: *Engine, ids: []const u32, c: Case) !?Diff { + const n = c.n; + const streams = c.streams; + // the trace waits on the stream layer by layer, which a capture cannot + const was = e.o.graphs; + e.o.graphs = false; + defer e.o.graphs = was; + if (n < 1 or n > 16) return error.BadWindow; + if (c.keep < 1 or c.keep > n) return error.BadKeep; + if (streams < 1 or streams > 8 or ids.len <= n + streams or streams * n > 64) return error.PromptTooShort; + const layers = e.model().spec.n_layers; + const rows = streams * n; + var serial: Sink = .{ .e = e, .bytes = undefined, .n = rows }; + var shared: Sink = .{ .e = e, .bytes = undefined, .n = rows }; + serial.bytes = try gpa.alloc(u8, (layers + 1) * rows * serial.width()); + defer gpa.free(serial.bytes); + shared.bytes = try gpa.alloc(u8, (layers + 1) * rows * shared.width()); + defer gpa.free(shared.bytes); + + // stream j: the ids short by j, its prompt all but its last n tokens + var alone: [8]qwen35.state.Caches = undefined; + var together: [8]qwen35.state.Caches = undefined; + var caches: [8]*qwen35.state.Caches = undefined; + var pos: [8]usize = undefined; + var tails: [8][]const u32 = undefined; + var made: usize = 0; + defer for (alone[0..made], together[0..made]) |*a1, *t1| { + a1.deinit(gpa); + t1.deinit(gpa); + }; + for (0..streams) |j| { + const end = ids.len - j; + const prompt = ids[0 .. end - n]; + tails[j] = ids[end - n .. end]; + pos[j] = prompt.len; + const req: qwen35.draw.Request = .{ .sampling = null, .position = prompt.len }; + alone[j] = try e.newCaches(ids.len + 8); + together[j] = e.newCaches(ids.len + 8) catch |err| { + alone[j].deinit(gpa); + return err; + }; + made += 1; + _ = try e.prefill(&alone[j], prompt, 0, null, req, null); + _ = try e.prefill(&together[j], prompt, 0, null, req, null); + caches[j] = &together[j]; + } + for (0..streams) |j| for (0..n) |i| { + serial.row = j * n + i; + const one = [1]*qwen35.state.Caches{&alone[j]}; + try round(e, &one, &.{pos[j] + i}, &.{tails[j][i..][0..1]}, 1, &serial, 0); + }; + try round(e, caches[0..streams], pos[0..streams], tails[0..streams], c.keep, &shared, c.pad); + // the rows past `keep` again, one at a time from the kept state, over the shared round's captures + for (c.keep..n) |i| for (0..streams) |j| { + shared.row = j * n + i; + const one = [1]*qwen35.state.Caches{&together[j]}; + try round(e, &one, &.{pos[j] + i}, &.{tails[j][i..][0..1]}, 1, &shared, 0); + }; + + const w = serial.width(); + for (0..layers + 1) |slot| for (0..rows) |r| { + const at = (slot * rows + r) * w; + if (std.mem.indexOfDiff(u8, serial.bytes[at..][0..w], shared.bytes[at..][0..w])) |col| { + const kind = if (slot == layers) "final" else if (e.model().spec.full(slot)) "full attention" else "linear attention"; + return .{ .layer = slot, .kind = kind, .stream = r / n, .row = r % n, .column = col / e.model().act.size() }; + } + }; + return null; +} + +pub fn run(gpa: std.mem.Allocator, io: std.Io, args: []const [:0]const u8) !void { + if (args.len < 2) return error.MissingArgument; + const n = if (args.len > 2) try std.fmt.parseInt(usize, args[2], 10) else 3; + const streams = if (args.len > 3) try std.fmt.parseInt(usize, args[3], 10) else 1; + const keep = if (args.len > 4) try std.fmt.parseInt(usize, args[4], 10) else n; + const ids = try ids_file.load(gpa, io, args[1]); + defer gpa.free(ids); + const e = try Engine.open(gpa, io, args[0], .{ .capacity = ids.len + 64, .prompt_rows = ids.len + 64, .streams = streams, .batch_rows = 128, .graphs = false, .policy = (try @import("group.zig").resolve("", 0)).policy }); + defer e.deinit(); + if (try runCase(gpa, e, ids, .{ .streams = streams, .n = n, .keep = keep })) |d| { + std.debug.print("FAIL layer {d} ({s}), stream {d} row {d} of {d}: first difference at column {d}\n", .{ d.layer, d.kind, d.stream, d.row, n, d.column }); + return error.Mismatch; + } + std.debug.print("PASS {d} streams of {d} rows, {d} kept: every layer's residuals and the final rows equal each stream one row at a time\n", .{ streams, n, keep }); +} diff --git a/zig/tests/qwen35/serve_cancel.py b/zig/tests/qwen35/serve_cancel.py new file mode 100644 index 00000000000..6669c824d30 --- /dev/null +++ b/zig/tests/qwen35/serve_cancel.py @@ -0,0 +1,50 @@ +"""A request cancelled in its prompt pass frees the server at once; usage: serve_cancel.py URL MODEL [PROMPT_WORDS].""" + +import http.client +import json +import socket +import sys +import time +import urllib.parse + +URL, MODEL = sys.argv[1], sys.argv[2] +WORDS = int(sys.argv[3]) if len(sys.argv) > 3 else 3000 +HOST = urllib.parse.urlparse(URL) + + +def body(text, max_tokens): + return json.dumps({"model": MODEL, "messages": [{"role": "user", "content": text}], "max_tokens": max_tokens, + "temperature": 0.0, "stream": False, "chat_template_kwargs": {"enable_thinking": False}}) + + +def short(): + conn = http.client.HTTPConnection(HOST.hostname, HOST.port, timeout=600) + began = time.perf_counter() + conn.request("POST", "/v1/chat/completions", body("Count from one to ten in words.", 32), {"Content-Type": "application/json"}) + text = json.load(conn.getresponse())["choices"][0]["message"]["content"] + conn.close() + return text, time.perf_counter() - began + + +def long_then_drop(nonce): + text = f"{nonce} " + " ".join(f"item{i % 97}x{(i * 7919) % 1013}" for i in range(WORDS)) + sock = socket.create_connection((HOST.hostname, HOST.port)) + payload = body(text, 8).encode() + sock.sendall(b"POST /v1/chat/completions HTTP/1.1\r\nHost: x\r\nContent-Type: application/json\r\nContent-Length: " + + str(len(payload)).encode() + b"\r\n\r\n" + payload) + time.sleep(0.4) + sock.close() + + +before, _ = short() +alone = min(short()[1] for _ in range(2)) +failed = 0 +for i in range(3): + long_then_drop(f"cancel{i}-{time.time_ns()}") + time.sleep(0.05) + after, waited = short() + ok = after == before and waited < alone + 3.0 + failed += not ok + print(("ok " if ok else "FAIL ") + f"cancel {i}: the next short request took {waited:.2f} s (alone {alone:.2f} s)", flush=True) +print("failed", failed) +sys.exit(1 if failed else 0) diff --git a/zig/tests/qwen35/serve_check.py b/zig/tests/qwen35/serve_check.py new file mode 100644 index 00000000000..081e0023a1e --- /dev/null +++ b/zig/tests/qwen35/serve_check.py @@ -0,0 +1,95 @@ +"""Exactness of a running native server over HTTP; usage: serve_check.py URL MODEL [TOKENS].""" + +import json +import sys +import threading +import time +import urllib.request + +URL, MODEL = sys.argv[1], sys.argv[2] +TOKENS = int(sys.argv[3]) if len(sys.argv) > 3 else 64 +PROMPTS = [ + "Write a short poem about the sea.", + "List the first twelve prime numbers, separated by commas.", + "Explain in two sentences why the sky is blue.", + "Count from one to thirty in words.", +] + + +def ask(messages, draft=True, temperature=0.0, seed=7): + body = {"model": MODEL, "messages": messages, "max_tokens": TOKENS, "temperature": temperature, "seed": seed, + "draft": draft, "chat_template_kwargs": {"enable_thinking": False}} + request = urllib.request.Request(URL + "/v1/chat/completions", json.dumps(body).encode(), + {"Content-Type": "application/json"}) + with urllib.request.urlopen(request, timeout=900) as reply: + doc = json.load(reply) + return doc["choices"][0]["message"]["content"], doc.get("usage", {}).get("prompt_tokens_details", {}) + + +def user(text): + return [{"role": "user", "content": text}] + + +def together(draft, temperature): + out = [None] * len(PROMPTS) + + def run(i): + out[i] = ask(user(PROMPTS[i]), draft, temperature)[0] + + threads = [threading.Thread(target=run, args=(i,)) for i in range(len(PROMPTS))] + for t in threads: + t.start() + for t in threads: + t.join() + return out + + +LONG = "Summarise this list in one sentence: " + " ".join(f"item{i % 97}x{(i * 7919) % 1013}" for i in range(500)) + + +def among_decoders(draft, temperature): + """A long prompt (a few thousand tokens, so several prompt chunks) sent while three streams decode.""" + out = [None] * 4 + + def run(i, text, delay): + time.sleep(delay) + out[i] = ask(user(text), draft, temperature)[0] + + threads = [threading.Thread(target=run, args=(i, PROMPTS[i], 0)) for i in range(3)] + threads.append(threading.Thread(target=run, args=(3, LONG, 0.5))) + for t in threads: + t.start() + for t in threads: + t.join() + return out + + +failed = 0 + + +def check(name, same): + global failed + failed += not same + print(("ok " if same else "FAIL ") + name, flush=True) + + +for label, temperature in (("greedy", 0.0), ("t0.8", 0.8)): + serial = [ask(user(p), False, temperature)[0] for p in PROMPTS] + drafted = [ask(user(p), True, temperature)[0] for p in PROMPTS] + check(f"{label}: drafted == serial", drafted == serial) + check(f"{label}: solo == together", together(True, temperature) == drafted) + check(f"{label}: serial together == serial solo", together(False, temperature) == serial) + again = [ask(user(p), True, temperature)[0] for p in PROMPTS] + check(f"{label}: the same twice", again == drafted) + # the long prompt first among the decoders (its prompt goes in a chunk a round), then alone (resumed from its cuts) + mixed = among_decoders(True, temperature) + check(f"{label}: decoders unchanged by a long prompt", mixed[:3] == drafted[:3]) + check(f"{label}: long prompt among decoders == alone", mixed[3] == ask(user(LONG), True, temperature)[0]) + check(f"{label}: serial long prompt among decoders == alone", among_decoders(False, temperature)[3] == mixed[3]) +first, _ = ask(user(PROMPTS[0]), True) +turn = user(PROMPTS[0]) + [{"role": "assistant", "content": first}, {"role": "user", "content": "Now say it shorter."}] +fresh, _ = ask(turn, False) +resumed, details = ask(turn, True) +check(f"resumed == fresh (cached {details})", resumed == fresh) +print("failed", failed) +sys.exit(1 if failed else 0) diff --git a/zig/tests/qwen35/serve_conc.py b/zig/tests/qwen35/serve_conc.py new file mode 100644 index 00000000000..2e1fe4de460 --- /dev/null +++ b/zig/tests/qwen35/serve_conc.py @@ -0,0 +1,76 @@ +"""A long prompt arriving while streams decode; usage: serve_conc.py URL MODEL [DECODERS] [PROMPT_WORDS] [TOKENS].""" + +import http.client +import json +import sys +import threading +import time +import urllib.parse + +URL, MODEL = sys.argv[1], sys.argv[2] +DECODERS = int(sys.argv[3]) if len(sys.argv) > 3 else 3 +WORDS = int(sys.argv[4]) if len(sys.argv) > 4 else 2400 +TOKENS = int(sys.argv[5]) if len(sys.argv) > 5 else 400 +HOST = urllib.parse.urlparse(URL) +SHORT = ["Write a long story about a lighthouse keeper.", "Explain how a transformer works, in detail.", + "List one hundred animals, one per line.", "Describe the history of Rome at length."] + + +def stream(text, max_tokens, stamps, temperature=0.0): + """One streamed chat request: the time of every content chunk goes to `stamps`; returns the text.""" + body = {"model": MODEL, "messages": [{"role": "user", "content": text}], "max_tokens": max_tokens, + "temperature": temperature, "stream": True, "chat_template_kwargs": {"enable_thinking": False}} + conn = http.client.HTTPConnection(HOST.hostname, HOST.port, timeout=900) + conn.request("POST", "/v1/chat/completions", json.dumps(body), {"Content-Type": "application/json"}) + reply = conn.getresponse() + out = [] + for raw in reply: + line = raw.decode().strip() + if not line.startswith("data:") or line.endswith("[DONE]"): + continue + delta = json.loads(line[5:])["choices"][0].get("delta", {}) + if delta.get("content"): + stamps.append(time.perf_counter()) + out.append(delta["content"]) + conn.close() + return "".join(out) + + +def long_prompt(nonce): + words = [f"{nonce}"] + [f"item{i % 97}x{(i * 7919) % 1013}" for i in range(WORDS)] + return "Summarise the following list in one short sentence.\n" + " ".join(words) + + +def run(label): + stamps = [[] for _ in range(DECODERS)] + threads = [threading.Thread(target=stream, args=(SHORT[i % len(SHORT)], TOKENS, stamps[i])) for i in range(DECODERS)] + for t in threads: + t.start() + while min(len(s) for s in stamps) < 16: + time.sleep(0.05) + sent = time.perf_counter() + first = [] + text = long_prompt(f"{label}-{time.time_ns()}") + t = threading.Thread(target=stream, args=(text, 16, first)) + t.start() + t.join() + done = time.perf_counter() + for th in threads: + th.join() + ttft = first[0] - sent + gaps = [] + tokens = 0 + for s in stamps: + for a, b in zip(s, s[1:]): + if b > sent and a < first[0]: + gaps.append(b - a) + tokens += sum(1 for x in s if sent <= x <= first[0]) + gaps.sort() + window = first[0] - sent + print(f"{label}: long prompt first token {ttft:.2f} s, decoding streams: longest gap {gaps[-1]:.2f} s, " + f"median gap {gaps[len(gaps) // 2] * 1000:.0f} ms, {tokens / window:.1f} tok/s over the prompt's window " + f"(the prompt ended at {done - sent:.2f} s)", flush=True) + + +for i in range(2): + run(f"run{i}") diff --git a/zig/tests/qwen35/serve_prefill.py b/zig/tests/qwen35/serve_prefill.py new file mode 100644 index 00000000000..54863a3bfc8 --- /dev/null +++ b/zig/tests/qwen35/serve_prefill.py @@ -0,0 +1,71 @@ +"""Cold prefill of a running server; usage: serve_prefill.py URL MODEL IDS.npy OUT_DIR [LENGTHS] [REPS].""" + +import json +import struct +import sys +import time +import urllib.error +import urllib.request +from pathlib import Path + + +def read_ids(path: Path) -> list[int]: + """The token ids of a 1-D little-endian int32 or int64 .npy file.""" + raw = path.read_bytes() + header_len = struct.unpack(" tuple[float, dict]: + """Seconds to the first streamed token and the final usage block; a refusal or a short prompt raises.""" + req = urllib.request.Request(url + "/v1/completions", json.dumps(body).encode(), {"Content-Type": "application/json"}) + began, first, usage = time.perf_counter(), None, {} + try: + with urllib.request.urlopen(req, timeout=3600) as r: + for line in r: + if not line.startswith(b"data: ") or line.strip() == b"data: [DONE]": + continue + event = json.loads(line[6:]) + if "error" in event: + raise SystemExit(f"refused: {event['error']}") + if first is None and event.get("choices") and event["choices"][0].get("text") is not None: + first = time.perf_counter() - began + usage = event.get("usage") or usage + except urllib.error.HTTPError as e: + raise SystemExit(f"refused: HTTP {e.code} {e.read().decode(errors='replace')[:300]}") + if first is None or usage.get("prompt_tokens") != len(body["prompt"]): + raise SystemExit(f"no prefill of {len(body['prompt'])} tokens: first token {first}, usage {usage}") + return first, usage + + +def main() -> int: + url, model, ids_path, out = sys.argv[1].rstrip("/"), sys.argv[2], Path(sys.argv[3]), Path(sys.argv[4]) + lengths = [int(n) for n in (sys.argv[5] if len(sys.argv) > 5 else "2048,8192,32768,65536").split(",")] + reps = int(sys.argv[6]) if len(sys.argv) > 6 else 3 + ids, rows = read_ids(ids_path), [] + out.mkdir(parents=True, exist_ok=True) + for n in lengths: + if n > len(ids): + print(f"skip {n}: the ids hold {len(ids)} tokens") + continue + body = {"model": model, "prompt": ids[:n], "max_tokens": 1, "temperature": 0, "stream": True, + "stream_options": {"include_usage": True}} + (out / f"request_{n}.json").write_text(json.dumps(body)) + times, cached = [], [] + for _ in range(reps): + seconds, usage = stream(url, body) + times.append(seconds) + cached.append((usage.get("prompt_tokens_details") or {}).get("cached_tokens", 0)) + best = sorted(times)[len(times) // 2] + rows.append({"tokens": n, "seconds": times, "median_tok_s": n / best, "cached_tokens": cached}) + print(f"prefill {n}: median {best:.3f} s, {n / best:.0f} tok/s, cached {cached}") + (out / "prefill.json").write_text(json.dumps(rows, indent=1)) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/zig/tests/qwen35/serve_prefix.py b/zig/tests/qwen35/serve_prefix.py new file mode 100644 index 00000000000..073db8486ba --- /dev/null +++ b/zig/tests/qwen35/serve_prefix.py @@ -0,0 +1,61 @@ +"""Prompt reuse of a running native server over HTTP; usage: serve_prefix.py URL MODEL [SYSTEM_WORDS].""" + +import json +import sys +import time +import urllib.request + +URL, MODEL = sys.argv[1], sys.argv[2] +WORDS = int(sys.argv[3]) if len(sys.argv) > 3 else 1500 +SYSTEM = "You are a careful assistant. Reference notes: " + " ".join(f"note{i % 89}x{(i * 7919) % 1013}" for i in range(WORDS)) +QUESTIONS = ["What is the first note?", "How many notes are there, roughly?", "Name the last note.", "Is note5x5 listed?"] + + +def ask(question, draft=True, system=SYSTEM): + """The reply's text, its time to the first token in milliseconds and the usage the server reports.""" + body = {"model": MODEL, "messages": [{"role": "system", "content": system}, {"role": "user", "content": question}], + "max_tokens": 16, "temperature": 0.0, "draft": draft, "stream": True, + "stream_options": {"include_usage": True}, "chat_template_kwargs": {"enable_thinking": False}} + request = urllib.request.Request(URL + "/v1/chat/completions", json.dumps(body).encode(), {"Content-Type": "application/json"}) + began = time.perf_counter() + first = None + text = "" + usage = {} + with urllib.request.urlopen(request, timeout=900) as reply: + for raw in reply: + line = raw.decode().strip() + if not line.startswith("data:") or line.endswith("[DONE]"): + continue + doc = json.loads(line[5:]) + if doc.get("usage"): + usage = doc["usage"] + for choice in doc.get("choices", []): + piece = choice.get("delta", {}).get("content") or "" + if piece and first is None: + first = (time.perf_counter() - began) * 1000 + text += piece + return text, first, usage + + +def cached(usage): + return (usage.get("prompt_tokens_details") or {}).get("cached_tokens", 0) + + +ask(QUESTIONS[0], True, "warm up the kernels: " + SYSTEM[:200]) +rows = [] +for label, question, draft in ( + ("first request (nothing kept)", QUESTIONS[0], True), + ("second request, same system prompt", QUESTIONS[1], True), + ("third request, same system prompt", QUESTIONS[2], True), + ("same system prompt, draft false (no cache)", QUESTIONS[3], False), + ("different system prompt of the same length", QUESTIONS[1], True), +): + system = SYSTEM if "different" not in label else SYSTEM.replace("note", "memo") + text, ttft, usage = ask(question, draft, system) + rows.append((label, usage.get("prompt_tokens", 0), cached(usage), ttft, text)) + print(f"{label}: prompt {rows[-1][1]} tokens, cached_tokens {rows[-1][2]}, time to first token {ttft:.0f} ms", flush=True) +# the same question with and without the cache: the replies must be equal +hit_text = ask(QUESTIONS[1], True)[0] +miss_text = ask(QUESTIONS[1], False)[0] +print("hit == miss:", hit_text == miss_text, flush=True) +sys.exit(0 if hit_text == miss_text else 1) diff --git a/zig/tests/qwen35/serve_rewind.py b/zig/tests/qwen35/serve_rewind.py new file mode 100644 index 00000000000..4b903ab922a --- /dev/null +++ b/zig/tests/qwen35/serve_rewind.py @@ -0,0 +1,60 @@ +"""Cache on equals cache off through rewinds; usage: serve_rewind.py CACHED_URL UNCACHED_URL MODEL [WORDS].""" + +import json +import sys +import urllib.request + +CACHED, UNCACHED, MODEL = sys.argv[1], sys.argv[2], sys.argv[3] +WORDS = int(sys.argv[4]) if len(sys.argv) > 4 else 1500 +SYSTEM = "You are a careful assistant. Reference notes: " + " ".join(f"note{i % 89}x{(i * 7919) % 1013}" for i in range(WORDS)) + + +def chat(url, messages, draft=True): + """The reply's text and the prompt tokens the server says it took from kept states.""" + body = {"model": MODEL, "messages": messages, "max_tokens": 48, "temperature": 0.0, "draft": draft, + "chat_template_kwargs": {"enable_thinking": False}} + request = urllib.request.Request(url + "/v1/chat/completions", json.dumps(body).encode(), {"Content-Type": "application/json"}) + with urllib.request.urlopen(request, timeout=900) as reply: + doc = json.loads(reply.read()) + cached = (doc.get("usage", {}).get("prompt_tokens_details") or {}).get("cached_tokens", 0) + return doc["choices"][0]["message"]["content"], cached + + +def script(): + """The steps of one conversation, each the messages a client sends; replies are filled in as they come.""" + system = {"role": "system", "content": SYSTEM} + return [ + ("turn 1", lambda h: [system, {"role": "user", "content": "What is the first note?"}]), + ("turn 2", lambda h: h["turn 1"] + [{"role": "user", "content": "And the second one?"}]), + ("turn 3", lambda h: h["turn 2"] + [{"role": "user", "content": "Is note5x5 listed?"}]), + ("regenerate turn 3", lambda h: h["turn 2"] + [{"role": "user", "content": "Is note5x5 listed?"}]), + ("edit turn 3", lambda h: h["turn 2"] + [{"role": "user", "content": "Is note7x7 listed?"}]), + ("delete turn 3, then turn 4", lambda h: h["turn 2"] + [{"role": "user", "content": "Name the last note."}]), + ("edit turn 1", lambda h: [system, {"role": "user", "content": "What is the third note?"}]), + ("turn 2 again", lambda h: h["turn 1"] + [{"role": "user", "content": "And the second one?"}]), + ] + + +def run(url, draft): + """Every step's reply on `url`; a step's history keeps the reply it got.""" + history, out = {}, [] + for name, build in script(): + messages = build(history) + text, cached = chat(url, messages, draft) + history[name] = messages + [{"role": "assistant", "content": text}] + out.append((name, text, cached)) + return out + + +bad = 0 +for draft in (True, False): + plain = run(UNCACHED, draft) + kept = run(CACHED, draft) + for (name, want, _), (_, got, cached) in zip(plain, kept): + ok = got == want + bad += not ok + print(f"{'PASS' if ok else 'FAIL'} rewind {name}, drafts {'on' if draft else 'off'}: {cached} prompt tokens from kept states") + if not ok: + print(f" without the cache: {want!r}\n with it: {got!r}") +print(f"rewind {'PASS' if bad == 0 else 'FAIL'}: {bad} differing replies") +sys.exit(1 if bad else 0) diff --git a/zig/tests/qwen35/serve_tp.sh b/zig/tests/qwen35/serve_tp.sh new file mode 100644 index 00000000000..fe495e03bd4 --- /dev/null +++ b/zig/tests/qwen35/serve_tp.sh @@ -0,0 +1,33 @@ +#!/bin/sh +# usage: serve_tp.sh DEVS WORLD MODEL_DIR PORT [serve flags]: serve_check.py on a tp server, from the build directory. +set -u +devs=$1; world=$2; model=$3; port=$4; shift 4 +bin=./zig-out/native-hip/bin/tensorfold-native +here=$(dirname "$0") +log=${TMPDIR:-/tmp}/serve_tp_$port +mkdir -p "$log" +pids="" +trap 'for p in $pids; do kill $p 2>/dev/null; done' EXIT +run() { exec env -u ROCR_VISIBLE_DEVICES HIP_VISIBLE_DEVICES=$devs "$bin" serve "$model" --tp "$world" --master 127.0.0.1 --master-port $((port + 1000)) --parallel 4 "$@"; } +r=1 +while [ "$r" -lt "$world" ]; do + run --rank $r "$@" > "$log/rank$r.log" 2>&1 & + pids="$pids $!" + r=$((r + 1)) +done +run --rank 0 --port "$port" --name m "$@" > "$log/rank0.log" 2>&1 & +head=$! +pids="$pids $head" +tries=0 +until curl -s "http://127.0.0.1:$port/health" > /dev/null; do + tries=$((tries + 1)) + if [ "$tries" -gt 600 ] || ! kill -0 "$head" 2>/dev/null; then echo "server did not start"; tail -n 5 "$log"/rank*.log; exit 1; fi + sleep 2 +done +python3 "$here/serve_check.py" "http://127.0.0.1:$port" m 64 +status=$? +kill "$head" +wait "$head" 2>/dev/null +for p in $pids; do wait "$p" 2>/dev/null; done +grep -hE "error|panic|FAIL" "$log"/rank*.log | head -5 +exit $status diff --git a/zig/tests/qwen35/truth_score.zig b/zig/tests/qwen35/truth_score.zig new file mode 100644 index 00000000000..9be0e2fc965 --- /dev/null +++ b/zig/tests/qwen35/truth_score.zig @@ -0,0 +1,211 @@ +//! Candidate logits scored against a high-precision truth .npy as tools/truth/score.py scores them, a block at a time. + +const std = @import("std"); +const npy = @import("npy"); +const Kind = @import("logit_kind.zig").Kind; + +/// One row's numbers. +const Row = struct { kl: f64, agree: bool, max_abs: f64, nll_truth: f64, nll_cand: f64 }; + +fn elem(wide: bool, bytes: []const u8, i: usize) f64 { + return if (wide) @bitCast(std.mem.readInt(u64, bytes[i * 8 ..][0..8], .little)) else @as(f32, @bitCast(std.mem.readInt(u32, bytes[i * 4 ..][0..4], .little))); +} + +/// `truth` and `cand` rows (the candidate's first `cols` logits), `target` the token the row predicts, if any. +fn scoreRow(wide: bool, truth: []const u8, kind: Kind, cand: []const u8, cols: usize, target: ?u32) Row { + var mt: f64 = -std.math.inf(f64); + var mc: f64 = -std.math.inf(f64); + var at: usize = 0; + var ac: usize = 0; + var max_abs: f64 = 0; + for (0..cols) |i| { + const t = elem(wide, truth, i); + const c = kind.at(cand[i * kind.size() ..]); + if (t > mt) { + mt = t; + at = i; + } + if (c > mc) { + mc = c; + ac = i; + } + max_abs = @max(max_abs, @abs(t - c)); + } + // KL = sum p (t - c) - (lse_t - lse_c), with p the truth's softmax + var zt: f64 = 0; + var zc: f64 = 0; + var a: f64 = 0; + for (0..cols) |i| { + const t = elem(wide, truth, i); + const c = kind.at(cand[i * kind.size() ..]); + const et = @exp(t - mt); + zt += et; + zc += @exp(c - mc); + a += et * (t - c); + } + const lse_t = mt + @log(zt); + const lse_c = mc + @log(zc); + var r: Row = .{ .kl = a / zt - (lse_t - lse_c), .agree = at == ac, .max_abs = max_abs, .nll_truth = 0, .nll_cand = 0 }; + if (target) |g| { + r.nll_truth = lse_t - elem(wide, truth, g); + r.nll_cand = lse_c - kind.at(cand[g * kind.size() ..]); + } + return r; +} + +pub const Score = struct { + rows: usize, + kl_mean: f64, + kl_max: f64, + /// Percent of rows whose top logit is the truth's. + top1: f64, + max_abs: f64, + ppl: f64, + ppl_truth: f64, +}; + +pub const Scorer = struct { + gpa: std.mem.Allocator, + io: std.Io, + file: std.Io.File, + wide: bool, + /// Where the data starts in the file, the rows, and the logits a row. + offset: u64, + rows: usize, + cols: usize, + kind: Kind, + /// The width of a candidate row (at least `cols`: the padded vocabulary). + width: usize, + /// The token each row predicts (the ids shifted by one; the last row has none). + ids: []const u32, + raw: []u8, + scored: []Row, + seen: usize = 0, + threads: usize, + + pub const block = 32; + + pub fn init(gpa: std.mem.Allocator, io: std.Io, path: []const u8, ids: []const u32, kind: Kind, width: usize) !Scorer { + const file = try std.Io.Dir.cwd().openFile(io, path, .{}); + errdefer file.close(io); + var head: [1024]u8 = undefined; + const n = try file.readPositionalAll(io, &head, 0); + const a = try npy.parse(head[0..n]); + if (a.rank != 2) return error.BadTruth; + const wide = std.mem.eql(u8, a.descr, " width) return error.TruthShape; + const raw = try gpa.alloc(u8, block * a.shape[1] * @as(usize, if (wide) 8 else 4)); + errdefer gpa.free(raw); + const scored = try gpa.alloc(Row, ids.len); + return .{ .gpa = gpa, .io = io, .file = file, .wide = wide, .offset = n - a.data.len, .rows = a.shape[0], .cols = a.shape[1], .kind = kind, .width = width, .ids = ids, .raw = raw, .scored = scored, .threads = @min(16, std.Thread.getCpuCount() catch 1) }; + } + + pub fn deinit(s: *Scorer) void { + s.gpa.free(s.scored); + s.gpa.free(s.raw); + s.file.close(s.io); + } + + /// Starts a new pass over the rows. + pub fn reset(s: *Scorer) void { + s.seen = 0; + } + + const Work = struct { + s: *const Scorer, + first: usize, + bytes: []const u8, + count: usize, + from: usize, + step: usize, + + fn go(w: Work) void { + const s = w.s; + const elem_size: usize = if (s.wide) 8 else 4; + var i = w.from; + while (i < w.count) : (i += w.step) { + const row = w.first + i; + const target: ?u32 = if (row + 1 < s.ids.len) s.ids[row + 1] else null; + s.scored[row] = scoreRow(s.wide, s.raw[i * s.cols * elem_size ..][0 .. s.cols * elem_size], s.kind, w.bytes[i * s.width * s.kind.size() ..][0 .. s.width * s.kind.size()], s.cols, target); + } + } + }; + + /// Scores rows `first..first + count` (candidate `bytes`, `width` logits a row) against the truth's. + pub fn put(ctx: *anyopaque, first: usize, count: usize, bytes: []const u8) anyerror!void { + const s: *Scorer = @ptrCast(@alignCast(ctx)); + if (first + count > s.rows) return error.TruthShape; + const elem_size: usize = if (s.wide) 8 else 4; + const n = count * s.cols * elem_size; + if (try s.file.readPositionalAll(s.io, s.raw[0..n], s.offset + first * s.cols * elem_size) != n) return error.TruthShort; + var spawned: [16]?std.Thread = @splat(null); + const t = @min(s.threads, count); + const base: Work = .{ .s = s, .first = first, .bytes = bytes, .count = count, .from = 0, .step = t }; + for (1..t) |k| { + var w = base; + w.from = k; + spawned[k] = std.Thread.spawn(.{}, Work.go, .{w}) catch null; + } + Work.go(base); + for (1..t) |k| if (spawned[k]) |th| th.join() else { + var w = base; + w.from = k; + Work.go(w); + }; + s.seen += count; + } + + pub fn result(s: *const Scorer) !Score { + if (s.seen != s.rows) return error.MissingRows; + var kl: f64 = 0; + var kl_max: f64 = 0; + var agree: usize = 0; + var max_abs: f64 = 0; + var nt: f64 = 0; + var nc: f64 = 0; + for (s.scored) |r| { + kl += r.kl; + kl_max = @max(kl_max, r.kl); + agree += @intFromBool(r.agree); + max_abs = @max(max_abs, r.max_abs); + nt += r.nll_truth; + nc += r.nll_cand; + } + const n: f64 = @floatFromInt(s.rows); + const targets: f64 = @floatFromInt(s.rows - 1); + return .{ .rows = s.rows, .kl_mean = kl / n, .kl_max = kl_max, .top1 = 100.0 * @as(f64, @floatFromInt(agree)) / n, .max_abs = max_abs, .ppl = @exp(nc / targets), .ppl_truth = @exp(nt / targets) }; + } +}; + +test { + _ = @import("logit_kind.zig"); +} + +test "a row scored against itself has no divergence" { + var truth: [4 * 8]u8 = undefined; + var cand: [4 * 4]u8 = undefined; + for ([_]f32{ 1.5, -2, 0.25, 3 }, 0..) |v, i| { + std.mem.writeInt(u64, truth[i * 8 ..][0..8], @bitCast(@as(f64, v)), .little); + std.mem.writeInt(u32, cand[i * 4 ..][0..4], @bitCast(v), .little); + } + const r = scoreRow(true, &truth, .f32, &cand, 4, 3); + try std.testing.expect(@abs(r.kl) < 1e-12); + try std.testing.expect(r.agree); + try std.testing.expectEqual(@as(f64, 0), r.max_abs); + try std.testing.expectApproxEqAbs(r.nll_truth, r.nll_cand, 1e-12); +} + +test "the divergence of a shifted row is the log-sum-exp gap" { + // truth (0, 0) is uniform, the candidate (0, ln 3) puts 3/4 on the second + var truth: [2 * 4]u8 = undefined; + var cand: [2 * 4]u8 = undefined; + std.mem.writeInt(u32, truth[0..4], @bitCast(@as(f32, 0)), .little); + std.mem.writeInt(u32, truth[4..8], @bitCast(@as(f32, 0)), .little); + std.mem.writeInt(u32, cand[0..4], @bitCast(@as(f32, 0)), .little); + std.mem.writeInt(u32, cand[4..8], @bitCast(@as(f32, @floatCast(@log(3.0)))), .little); + const r = scoreRow(false, &truth, .f32, &cand, 2, null); + const want = 0.5 * @log(0.5 / 0.25) + 0.5 * @log(0.5 / 0.75); + try std.testing.expectApproxEqAbs(want, r.kl, 1e-6); + try std.testing.expect(!r.agree); +}