diff --git a/CHANGELOG.md b/CHANGELOG.md index 2bbac8260fa..62a26cf284f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,10 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel ## Unreleased +- HIP: `serve` with `--drafter` runs Qwen3.8-27B's DFlash2 drafter on the HIP engine through the lane core, where it was refused, and the drafter's weights and per-stream contexts count in the memory plan (#3665, refs #1563). Thanks to @AbrahamCete. + +- HIP: an EXL3 input rotation and trellis linear kernel group (`exl3/exl3.hip`) at 2 to 8 bits, the HIP side of the projection DeepSeek-V4.1's CUDA path calls for its head, Engram's `wkv` and the indexer's `wk`, with sums in a fixed order so a row's bits do not depend on the rows beside it; nothing serves through it yet (#3314, refs #2065). Thanks to @Shoestring-dev. + - CLI: `tensorfold models` lists the chat checkpoints from the supported-models guide that fit this machine, largest first, with the memory each needs, a quality score from TensorFold Web's quality suite (receipts in `docs/receipts/quality-suite`) and a rough one-stream speed (measured on this chip, or estimated from another chip by memory bandwidth); `--all` adds the rest, `--json` adds `machine` and `catalog` to schema 1, and the cached checkpoints follow as before (#3483). - gpt-oss: a first host-only slice reads `openai/gpt-oss-20b`'s config and refuses unknown or unsupported fields by name, checks all 459 tensor names of the published checkpoint, and adds an MXFP4 reader for 32-value E2M1 blocks with UE8M0 scales that never rewrites checkpoint bytes; nothing is registered with the server yet (#3513). diff --git a/docs/community-benchmarks.md b/docs/community-benchmarks.md index bd7bc49bc8c..8d0e6ae2e68 100644 --- a/docs/community-benchmarks.md +++ b/docs/community-benchmarks.md @@ -12,7 +12,7 @@ tensorfold benchmark TensorFold/NVIDIA-Nemotron-3.5-Lightning-30B-A3B-MLX-4bit The examples call the command `tensorfold`. A source build's binary is `zig-out/native/bin/tensorfold-native`, and it takes the same arguments. -The command starts its own single-request `serve` on a loopback port, disables prompt reuse, warms each workload, and measures five repeats at sampled and greedy settings. It stops only the server it started, and a Ctrl-C or a closed terminal stops that server too; a second Ctrl-C exits at once and kills it. The default output limit is 256 tokens. The checkpoint must already be in the cache: `tensorfold benchmark` never downloads, so run `tensorfold pull` first. `--drafter DIR_OR_REPO` passes a drafter to engines that take one. Drafts stay on by default, and only `--serial` disables them. The default `--drafter auto` passes the target's own drafter when it is already cached (`z-lab/Qwen3.8-27B-DFlash2` for Qwen3.8-27B) and names it in the run output and the receipt; when it is not cached, the run passes none and says why. `--drafter none` passes none. When `--serial` overrides a given `--drafter`, the run prints a line saying so. The HIP engine runs no DFlash2 drafter yet, so a ROCm run passes none: a named `--drafter` is refused before the run starts, and `--drafter auto` on a checkpoint with its own drafter, such as Qwen3.8-27B, says the run passes no drafter, so the receipt's `drafter_repo_id` is null. `serve --drafter` on the HIP engine is refused before it loads. Without a drafter the HIP engine still drafts on its own, with the model's MTP head where the checkpoint has one and with copies from the stream's own context, so a ROCm run without a drafter is not a plain run; `--serial` gives one. +The command starts its own single-request `serve` on a loopback port, disables prompt reuse, warms each workload, and measures five repeats at sampled and greedy settings. It stops only the server it started, and a Ctrl-C or a closed terminal stops that server too; a second Ctrl-C exits at once and kills it. The default output limit is 256 tokens. The checkpoint must already be in the cache: `tensorfold benchmark` never downloads, so run `tensorfold pull` first. `--drafter DIR_OR_REPO` passes a drafter to engines that take one. Drafts stay on by default, and only `--serial` disables them. The default `--drafter auto` passes the target's own drafter when it is already cached (`z-lab/Qwen3.8-27B-DFlash2` for Qwen3.8-27B) and names it in the run output and the receipt; when it is not cached, the run passes none and says why. `--drafter none` passes none. When `--serial` overrides a given `--drafter`, the run prints a line saying so. On ROCm the HIP engine runs DFlash2 over the dense `qwen3_5` checkpoints, so a named `--drafter` passes it to them; for any other family a ROCm run refuses a named `--drafter` before the run starts. `--drafter auto` passes none on ROCm: a ROCm run drafts with a drafter only when one is named, and on a checkpoint with its own drafter, such as Qwen3.8-27B, `auto` says the run passes no drafter, so the receipt's `drafter_repo_id` is null. Without a drafter the HIP engine still drafts on its own, with the model's MTP head where the checkpoint has one and with copies from the stream's own context, so a ROCm run without a drafter is not a plain run; `--serial` gives one. A managed run sizes its served context as `serve` does, unless `--context N` (1 through 10,000,000) names the prompt plus reply capacity, and serves a bf16 attention cache unless `--kv-cache fp8` says otherwise. An attached diff --git a/docs/kernel-contract.md b/docs/kernel-contract.md index b860e4d473b..f08f80d29b5 100644 --- a/docs/kernel-contract.md +++ b/docs/kernel-contract.md @@ -371,6 +371,13 @@ HIP also checks Flash Next's indexer block score kernel (`tf_fn_idx_scores`, `co `hip_records_sparse.zig`): staging each tile's rows of `q` in LDS when `heads * dims <= 512`, checked against the fp64 relu-summed head dots with one control leaving out each row's last head (`shapes`). +HIP also checks EXL3's projections for decode rows (`exl3/exl3.hip`, CUDA's `exl3_block/linear.cu`): `tf_exl3_rot_in` +(bf16 rows times suh, rotated by 128 and rounded to fp16) and `tf_exl3_linear` at 2, 3, 4, 5, 6 and 8 bits (mul1) on 4 +and 8 waves, each against float64 at deepseek_v41's indexer wk and Engram wkv (and its head at 8 bits) and the plan's +8-wave edge. The linear's gate 4 is exact: all-ones trellis states give one weight (-0.651 at every width), so 6144 +terms of 4096 times it stay integers under 2^24 where fp16 overflows. Two controls: rot_in reading the next block's suh, +and the linear reading its input rows one row late. + On gfx12, HIP also checks the WMMA dense tile (`dense_wmma12_gemm`, both block geometries, fp32 and BF16 out). The small block meets its depth-k bound. The big block (64-deep K steps over swizzled LDS rows) replaces the 32-deep block it was before #2245's second lever, byte for byte: gate 3 runs a frozen copy of that block (`tf_ref_wmma12_k32`, in the diff --git a/docs/recipes/qwen3.8-27b.md b/docs/recipes/qwen3.8-27b.md index 76485984510..c324a01cb63 100644 --- a/docs/recipes/qwen3.8-27b.md +++ b/docs/recipes/qwen3.8-27b.md @@ -219,12 +219,21 @@ tensorfold serve TensorFold/Qwen3.8-27B-MLX-4bit --name bench DFlash2 is used automatically once pulled. On MLX, `--drafter none` disables that draft model; `--no-drafts` disables all drafts on either backend. CUDA requires DFlash2 unless `--no-drafts` is set. -The HIP engine runs no DFlash2 drafter yet: `serve --drafter` is refused before the engine opens the GPU or -loads any weights. Refusing DFlash2 does not turn off the engine's own drafts: the model's MTP head where the +On HIP, `serve --drafter DIR` runs the DFlash2 drafter over the dense checkpoints: the target taps the +drafter's layers into a ring beside each stream's caches, budgeted before the streams are sized, and the +drafter's chains reach the round loop through the lane core's drafter wrapper. It runs on one rank at 4 bits: +`--drafter` with `--tp` above 1 and `--drafter-bits 0` are refused before any load, and the other HIP families +(the sparse `qwen3_5_moe` among them) refuse `--drafter` by name, as BF16 checkpoints do: the engine times no +BF16 windows to price the drafter's rounds. Prompts reach the drafter whole, as their prompt pass ends. +Without `--drafter` the engine still drafts on its own: the model's MTP head where the checkpoint has one, and copies from the stream's own context. `TensorFold/Qwen3.8-27B-MLX-4bit` has no MTP -head, so on HIP it drafts copies only. `--mtp-drafts 0` stops the MTP head's drafts alone; `--no-drafts` turns -both off and decodes plain. +head, so on HIP it then drafts copies only. `--mtp-drafts 0` stops the MTP head's drafts alone; `--no-drafts` +turns every draft off (the drafter is not loaded) and decodes plain. The target verifies every proposed token against its own serial sample. +`tf-qwen35-test check --drafter DIR` (`zig build tf-qwen35-test -Dhip=true`) runs the HIP model checks +with the drafter in front of the target, opened as the server opens it, so the lane checks compare drafted +replies with serial ones (greedy and seeded), solo with together and graph with eager under the drafter; without +`--drafter` the 27B has no draft head and skips the drafted == serial checks. ## CUDA diff --git a/zig/build/hip.zig b/zig/build/hip.zig index 558f908831a..fe6e8172a29 100644 --- a/zig/build/hip.zig +++ b/zig/build/hip.zig @@ -278,14 +278,14 @@ pub fn steps(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.buil .imports = &.{ .{ .name = "hip", .module = gpu.hip }, .{ .name = "core", .module = gpu.hip.import_table.get("core").? }, .{ .name = "lighton_ocr", .module = gpu.lighton } }, }) }); b.step("tf-lighton-hip-capture", "Capture native HIP LightOnOCR stages against a local reference fixture").dependOn(&b.addInstallArtifact(lighton_capture, .{}).step); - const qwen_capture_host = captureQwen(b, b.graph.host, host); + const qwen_capture_host = @import("lighton_hip.zig").captureQwen(b, b.graph.host, host); b.step("check-qwen-hip-capture-host", "Compile the Qwen HIP fixture capture without device execution").dependOn(&qwen_capture_host.step); - const qwen_capture_gpu = captureQwen(b, target, gpu); + const qwen_capture_gpu = @import("lighton_hip.zig").captureQwen(b, target, gpu); b.step("tf-qwen-hip-capture", "Capture native Qwen HIP stages against local reference fixtures").dependOn(&b.addInstallArtifact(qwen_capture_gpu, .{}).step); for ([_][]const u8{ "lighton", "qwen" }) |family_name| { - const exact_host = exactTool(b, b.graph.host, host, family_name); + const exact_host = @import("lighton_hip.zig").exactTool(b, b.graph.host, host, family_name); b.step(b.fmt("check-{s}-hip-exact-host", .{family_name}), "Compile native HIP image consistency checks without execution").dependOn(&exact_host.step); - const exact_gpu = exactTool(b, target, gpu, family_name); + const exact_gpu = @import("lighton_hip.zig").exactTool(b, target, gpu, family_name); b.step(b.fmt("tf-{s}-hip-exact", .{family_name}), "Build native HIP image consistency checks").dependOn(&b.addInstallArtifact(exact_gpu, .{}).step); } const native = server(b, target, gpu, build_options); @@ -478,25 +478,6 @@ pub fn server(b: *std.Build, target: std.Build.ResolvedTarget, e: Engine, build_ _ = @import("server.zig").addTo(b, exe.root_module, target, .ReleaseSafe); return exe; } -fn captureQwen(b: *std.Build, target: std.Build.ResolvedTarget, e: Engine) *std.Build.Step.Compile { - return b.addExecutable(.{ .name = "tf-qwen-hip-capture", .root_module = b.createModule(.{ - .root_source_file = b.path("zig/tests/lighton_hip/qwen_capture.zig"), - .target = target, - .optimize = .ReleaseSafe, - .link_libc = true, - .imports = &.{ .{ .name = "hip", .module = e.hip }, .{ .name = "core", .module = e.hip.import_table.get("core").? }, .{ .name = "qwen3_5", .module = e.family }, .{ .name = "lanes", .module = e.lanes }, .{ .name = "qwen_hip_vision", .module = e.family.import_table.get("qwen_hip_vision").? } }, - }) }); -} -fn exactTool(b: *std.Build, target: std.Build.ResolvedTarget, e: Engine, family_name: []const u8) *std.Build.Step.Compile { - const file = if (std.mem.eql(u8, family_name, "lighton")) "exact.zig" else "qwen_exact.zig"; - return b.addExecutable(.{ .name = b.fmt("tf-{s}-hip-exact", .{family_name}), .root_module = b.createModule(.{ - .root_source_file = b.path(b.fmt("zig/tests/lighton_hip/{s}", .{file})), - .target = target, - .optimize = .ReleaseSafe, - .link_libc = true, - .imports = &.{ .{ .name = "hip", .module = e.hip }, .{ .name = "core", .module = e.hip.import_table.get("core").? }, .{ .name = "lighton_ocr", .module = e.lighton }, .{ .name = "qwen3_5", .module = e.family }, .{ .name = "lanes", .module = e.lanes }, .{ .name = "qwen_hip_vision", .module = e.family.import_table.get("qwen_hip_vision").? } }, - }) }); -} /// A group's source and whether it compiles with IEEE arithmetic (`strict`: -O2 -fno-fast-math, IEEE denormals). const Source = struct { path: []const u8, strict: bool = false }; /// The model-free kernels' source groups, in zig/src/hip/kernels.zig's Group order. @@ -517,6 +498,7 @@ const groups = [_]Source{ .{ .path = "lighton_ocr.hip", .strict = true }, .{ .path = "qwen_vision.hip", .strict = true }, .{ .path = "draft/draft.hip" }, + .{ .path = "exl3/exl3.hip" }, }; /// What the group sources include, so an edit to one rebuilds them. const headers = [_][]const u8{ diff --git a/zig/build/lighton_hip.zig b/zig/build/lighton_hip.zig index 2d576f552b4..3e6846d0dfa 100644 --- a/zig/build/lighton_hip.zig +++ b/zig/build/lighton_hip.zig @@ -1,5 +1,6 @@ -//! HIP LightOnOCR module construction and host checks, using the native server's shared engine types. +//! HIP LightOnOCR modules, host checks and the zig/tests/lighton_hip tools, on the server's shared engine types. const std = @import("std"); +const Engine = @import("hip.zig").Engine; pub fn module(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builtin.OptimizeMode, hip: *std.Build.Module, core: *std.Build.Module, lanes: *std.Build.Module, api: *std.Build.Module, serve: *std.Build.Module) *std.Build.Module { return b.createModule(.{ .root_source_file = b.path("zig/src/families/lighton_ocr/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 }, .{ .name = "hip_serve", .module = serve } } }); @@ -14,3 +15,24 @@ pub fn host(b: *std.Build, m: *std.Build.Module, step: *std.Build.Step) void { b.step("test-lighton-hip-host", "LightOnOCR HIP image, state and admission tests without devices").dependOn(&run.step); step.dependOn(&run.step); } + +pub fn captureQwen(b: *std.Build, target: std.Build.ResolvedTarget, e: Engine) *std.Build.Step.Compile { + return b.addExecutable(.{ .name = "tf-qwen-hip-capture", .root_module = b.createModule(.{ + .root_source_file = b.path("zig/tests/lighton_hip/qwen_capture.zig"), + .target = target, + .optimize = .ReleaseSafe, + .link_libc = true, + .imports = &.{ .{ .name = "hip", .module = e.hip }, .{ .name = "core", .module = e.hip.import_table.get("core").? }, .{ .name = "qwen3_5", .module = e.family }, .{ .name = "lanes", .module = e.lanes }, .{ .name = "qwen_hip_vision", .module = e.family.import_table.get("qwen_hip_vision").? } }, + }) }); +} + +pub fn exactTool(b: *std.Build, target: std.Build.ResolvedTarget, e: Engine, family_name: []const u8) *std.Build.Step.Compile { + const file = if (std.mem.eql(u8, family_name, "lighton")) "exact.zig" else "qwen_exact.zig"; + return b.addExecutable(.{ .name = b.fmt("tf-{s}-hip-exact", .{family_name}), .root_module = b.createModule(.{ + .root_source_file = b.path(b.fmt("zig/tests/lighton_hip/{s}", .{file})), + .target = target, + .optimize = .ReleaseSafe, + .link_libc = true, + .imports = &.{ .{ .name = "hip", .module = e.hip }, .{ .name = "core", .module = e.hip.import_table.get("core").? }, .{ .name = "lighton_ocr", .module = e.lighton }, .{ .name = "qwen3_5", .module = e.family }, .{ .name = "lanes", .module = e.lanes }, .{ .name = "qwen_hip_vision", .module = e.family.import_table.get("qwen_hip_vision").? } }, + }) }); +} diff --git a/zig/kernels/hip/exl3/exl3.hip b/zig/kernels/hip/exl3/exl3.hip new file mode 100644 index 00000000000..065e151ba96 --- /dev/null +++ b/zig/kernels/hip/exl3/exl3.hip @@ -0,0 +1,332 @@ +// EXL3 projections for decode rows (CUDA's exl3_block/linear.cu): the input rotation, then the trellis linear (mul1). + +#include "ops/common.hpp" + +namespace { + +typedef _Float16 h2 __attribute__((ext_vector_type(2))); +typedef float f32x8 __attribute__((__vector_size__(8 * sizeof(float)))); + +constexpr float kHadScale = 0.08838834764831845f; // 1 / sqrt(128), CUDA's HAD_SCALE + +// An fp32 value the compiler cannot fold into the next conversion (fp16(a * b) would otherwise round once, not twice). +__device__ __forceinline__ float opaque(float x) { + asm volatile("" : "+v"(x)); + return x; +} + +// A pointer in the global address space, so its loads are not flat loads that an LDS wait would also wait for. +template +__device__ __forceinline__ const __attribute__((address_space(1))) T* gl(const T* p) { + return (const __attribute__((address_space(1))) T*)p; +} + +// The unscaled 128-point Walsh-Hadamard transform, 4 values a lane (4 lane + j), in CUDA's fwht128 butterfly order. +__device__ __forceinline__ void fwht128(float (&v)[4], int lane) { + const float a = v[0] + v[1], b = v[0] - v[1], c = v[2] + v[3], d = v[2] - v[3]; + v[0] = a + c; + v[1] = b + d; + v[2] = a - c; + v[3] = b - d; +#pragma unroll + for (int m = 1; m < 32; m <<= 1) { +#pragma unroll + for (int j = 0; j < 4; ++j) { + const float o = __shfl_xor(v[j], m, 32); + v[j] = (lane & m) ? o - v[j] : v[j] + o; + } + } +} + +// E(p): one past the last stream bit of value p's 16-bit window (exl3_format.zig streamEnds). +template +__host__ __device__ constexpr int stream_end(int p) { + return (K2 & 1) ? ((p + 1) * K2 - ((p + 1) & 1)) / 2 : (p + 1) * (K2 / 2); +} + +// Lane l (column c = l % 16, k half h = l / 16) decodes rows 8 h + 2 q, + 1 of column c: its windows' words, shift. +template +struct LaneWin { + static constexpr int TW = 4 * K2; + static constexpr int D = stream_end(1) - stream_end(0); + int hi[4], lo[4], sh[4]; + __device__ __forceinline__ explicit LaneWin(int lane) { + const int c = lane & 15, h = lane >> 4; +#pragma unroll + for (int q = 0; q < 4; ++q) { + const int p0 = 32 * (c & 7) + 8 * q + 4 * (c >> 3) + 2 * h; + const int s = (stream_end(p0) - 16 + 128 * K2) % (128 * K2); + const int o = s & 31; + hi[q] = s >> 5; + lo[q] = o ? (hi[q] + 1) % TW : hi[q]; + sh[q] = (32 - o) & 31; + } + } +}; + +// Two consecutive values from the 32 stream bits at the first window: fp16(0x6400 + bytesum(s * 0x83DCD12D)) fused. +template +__device__ __forceinline__ uint32_t decode_pair(uint32_t u) { + const uint32_t w0 = u >> 16; + const uint32_t w1 = __builtin_amdgcn_ubfe(u, 16 - D, 16); + const uint32_t s0 = __builtin_amdgcn_sad_u8(w0 * 0x83DCD12Du, 0u, 0x64006400u); + const uint32_t s = __builtin_amdgcn_sad_hi_u8(w1 * 0x83DCD12Du, 0u, s0); + h2 hv = __builtin_bit_cast(h2, s); + hv = __builtin_elementwise_fma(hv, __builtin_bit_cast(h2, 0x1eee1eeeu), __builtin_bit_cast(h2, 0xc931c931u)); + return __builtin_bit_cast(uint32_t, hv); +} + +// This lane's 8 values of the tile at `tw`, as four fp16 pairs (rows 8 h + 2 q, 8 h + 2 q + 1 of column c). +template +__device__ __forceinline__ void decode_own(const uint32_t* tw, const LaneWin& w, uint32_t (&own)[4]) { +#pragma unroll + for (int q = 0; q < 4; ++q) { + const uint32_t u = __builtin_amdgcn_alignbit(tw[w.hi[q]], tw[w.lo[q]], w.sh[q]); + own[q] = decode_pair::D>(u); + } +} + +__device__ __forceinline__ float dot2(uint32_t a, uint32_t b, float c) { + return __builtin_amdgcn_fdot2(__builtin_bit_cast(h2, a), __builtin_bit_cast(h2, b), c, false); +} + +__device__ __forceinline__ float partner(float x) { + const uint32_t u = __builtin_bit_cast(uint32_t, x); + return __builtin_bit_cast(float, __builtin_amdgcn_permlanex16(u, u, 0x76543210u, 0xfedcba98u, false, false)); +} + +__device__ __forceinline__ void lds_fence() { + __builtin_amdgcn_wave_barrier(); + asm volatile("s_waitcnt lgkmcnt(0)" ::: "memory"); +} + +// One wave's k tiles [kt0, kt0 + n) of a 128-column strip against one row: a lane's dot2 chain, then the half-waves'. +template +__device__ __forceinline__ void strip_1row(const uint32_t* tiles, long long step, int kt0, int n, const _Float16* xrow, + uint32_t* st, int lane, f32x8 (&acc)[8]) { + constexpr int TW = 4 * K2, LW = 8 * TW / 32; + if (n <= 0) return; + const LaneWin win(lane); + const int h = lane >> 4; + float s[8]; +#pragma unroll + for (int t = 0; t < 8; ++t) s[t] = 0.f; + uint32_t pf[LW]; + uint4 xa; + { + const uint32_t* p = tiles + (long long)kt0 * step; +#pragma unroll + for (int i = 0; i < LW; ++i) pf[i] = __builtin_nontemporal_load(gl(p) + i * 32 + lane); + xa = *gl(reinterpret_cast(xrow + 16 * kt0 + 8 * h)); + } + for (int j = 0; j < n; ++j) { +#pragma unroll + for (int i = 0; i < LW; ++i) st[i * 32 + lane] = pf[i]; + const uint4 x = xa; + if (j + 1 < n) { + const uint32_t* p = tiles + (long long)(kt0 + j + 1) * step; +#pragma unroll + for (int i = 0; i < LW; ++i) pf[i] = __builtin_nontemporal_load(gl(p) + i * 32 + lane); + xa = *gl(reinterpret_cast(xrow + 16 * (kt0 + j + 1) + 8 * h)); + } + lds_fence(); +#pragma unroll + for (int t = 0; t < 8; ++t) { + uint32_t own[4]; + decode_own(st + t * TW, win, own); + float a = dot2(own[0], x.x, s[t]); + a = dot2(own[1], x.y, a); + a = dot2(own[2], x.z, a); + s[t] = dot2(own[3], x.w, a); + } + __builtin_amdgcn_wave_barrier(); + } +#pragma unroll + for (int t = 0; t < 8; ++t) acc[t][0] += s[t] + partner(s[t]); +} + +// strip_1row's sums for up to RM rows, TT of the strip's tiles from t0, each tile decoded once for every row. +template +__device__ __forceinline__ void strip_rows_part(const uint32_t* tiles, long long step, int kt0, int n, + const _Float16* xlane, int R, uint32_t* st, uint4* xst, int lane, + f32x8 (&acc)[8]) { + constexpr int TW = 4 * K2, PW = TT * TW, RL = (PW + 31) / 32; + const LaneWin win(lane); + const int h = lane >> 4; + const bool xlive = (lane >> 1) < R; + const uint4* xl = reinterpret_cast(xlane + 8 * (lane & 1)); + const uint32_t* tp = tiles + t0 * TW; + float s[RM][TT]; +#pragma unroll + for (int r = 0; r < RM; ++r) +#pragma unroll + for (int t = 0; t < TT; ++t) s[r][t] = 0.f; + uint32_t pf[RL]; + uint4 xp = make_uint4(0u, 0u, 0u, 0u); + auto fetch = [&](int kt) { + const uint32_t* p = tp + (long long)kt * step; +#pragma unroll + for (int i = 0; i < RL; ++i) { + const int wi = i * 32 + lane; + pf[i] = wi < PW ? __builtin_nontemporal_load(gl(p) + wi) : 0u; + } + if (xlive) xp = *gl(xl + 2 * kt); + }; + fetch(kt0); + for (int j = 0; j < n; ++j) { +#pragma unroll + for (int i = 0; i < RL; ++i) { + const int wi = i * 32 + lane; + if (wi < PW) st[wi] = pf[i]; + } + xst[lane] = xp; + if (j + 1 < n) fetch(kt0 + j + 1); + lds_fence(); + uint32_t own[TT][4]; +#pragma unroll + for (int t = 0; t < TT; ++t) decode_own(st + t * TW, win, own[t]); +#pragma unroll + for (int r = 0; r < RM; ++r) { + if (r < R) { + const uint4 x = xst[2 * r + h]; +#pragma unroll + for (int t = 0; t < TT; ++t) { + float a = dot2(own[t][0], x.x, s[r][t]); + a = dot2(own[t][1], x.y, a); + a = dot2(own[t][2], x.z, a); + s[r][t] = dot2(own[t][3], x.w, a); + } + } + } + __builtin_amdgcn_wave_barrier(); + } + // lane l holds row 2 i + h of each pair as WMMA's C layout does: its half's sum plus its partner's, as strip_1row +#pragma unroll + for (int t = 0; t < TT; ++t) { + float v[8]; +#pragma unroll + for (int i = 0; i < 8; ++i) { + if (2 * i + 1 < RM) { + const float s0 = s[2 * i][t], s1 = s[2 * i + 1][t]; + const float o0 = partner(s0), o1 = partner(s1); + v[i] = h ? s1 + o1 : s0 + o0; + } else { + v[i] = 0.f; + } + } + acc[t0 + t] += (f32x8){v[0], v[1], v[2], v[3], v[4], v[5], v[6], v[7]}; + } +} + +// Up to 8 rows take the strip's 8 tiles at once; 9 to 16 rows take them in two parts of 4 (the sums stay in registers). +template +__device__ __forceinline__ void strip_rows(const uint32_t* tiles, long long step, int kt0, int n, const _Float16* xlane, + int R, uint32_t* st, uint4* xst, int lane, f32x8 (&acc)[8]) { + if (n <= 0) return; + if (R <= 8) { + strip_rows_part(tiles, step, kt0, n, xlane, R, st, xst, lane, acc); + } else { + strip_rows_part(tiles, step, kt0, n, xlane, R, st, xst, lane, acc); + __builtin_amdgcn_wave_barrier(); + strip_rows_part(tiles, step, kt0, n, xlane, R, st, xst, lane, acc); + } +} + +// y = (xh @ W_q) H / sqrt(128) * svh for a 128-column block: wave w sums k tiles w K/16/WK on; rows in passes of 16. +template +__device__ __forceinline__ void linear_body(const __half* xh_, const uint32_t* T, long long stride_k, + long long stride_nb, const __half* svh, void* y, int y_kind, int M, int K, + int N) { + constexpr int TW = 4 * K2; + extern __shared__ __attribute__((aligned(16))) float red[]; // WK * min(M, 8) * 128 floats + __shared__ __attribute__((aligned(16))) uint32_t stage[WK][8 * TW]; + const _Float16* xh = reinterpret_cast(xh_); + const int RH = M < 8 ? M : 8; + const int nb = blockIdx.x, wave = threadIdx.x >> 5, lane = threadIdx.x & 31; + const int per_wave = (K >> 4) / WK, kt0 = wave * per_wave; + const uint32_t* tiles = T + nb * stride_nb; + const int col = nb * 128 + 4 * lane; + for (int m0 = 0; m0 < M; m0 += 16) { + const int R = min(16, M - m0); + f32x8 acc[8]; +#pragma unroll + for (int t = 0; t < 8; ++t) acc[t] = (f32x8){0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f}; + // a row's sums are the same bits whatever rows share its pass; the rows' inputs stage in the wave's red floats + if (R == 1) { + strip_1row(tiles, stride_k, kt0, per_wave, xh + (size_t)m0 * K, stage[wave], lane, acc); + } else { + const int ar = m0 + min(lane >> 1, R - 1); + strip_rows(tiles, stride_k, kt0, per_wave, xh + (size_t)ar * K, R, stage[wave], + reinterpret_cast(red + wave * 128), lane, acc); + } +#pragma unroll + for (int hp = 0; hp < 2; ++hp) { + const int rlo = 8 * hp; + if (rlo >= R) break; + const int rn = min(R - rlo, 8); + __syncthreads(); +#pragma unroll + for (int t = 0; t < 8; ++t) +#pragma unroll + for (int i = 0; i < 4; ++i) { + const int rr = 2 * i + (lane >> 4); + if (rr < RH) red[(wave * RH + rr) * 128 + t * 16 + (lane & 15)] = acc[t][4 * hp + i]; + } + __syncthreads(); + // the waves' sums in wave order, then the output rotation and svh as CUDA's finish does them + for (int r = wave; r < rn; r += WK) { + const float4 u = *reinterpret_cast(red + r * 128 + 4 * lane); + float v[4] = {u.x, u.y, u.z, u.w}; +#pragma unroll + for (int w = 1; w < WK; ++w) { + const float4 q = *reinterpret_cast(red + (w * RH + r) * 128 + 4 * lane); + v[0] += q.x; + v[1] += q.y; + v[2] += q.z; + v[3] += q.w; + } + fwht128(v, lane); + const long long row = (long long)(m0 + rlo + r) * N + col; +#pragma unroll + for (int j = 0; j < 4; ++j) store(y, y_kind, row + j, v[j] * kHadScale * __half2float(svh[col + j])); + } + } + __syncthreads(); + } +} + +} // namespace + +// xh = fp16((x * suh) H / sqrt(128)) a 128-wide block a wave, four a workgroup, a row a grid row (CUDA's rot_in). +extern "C" __global__ void __launch_bounds__(128) +tf_exl3_rot_in(const void* x, int x_kind, const __half* suh, __half* xh, int K) { + const int blk = blockIdx.x * 4 + (threadIdx.x >> 5), lane = threadIdx.x & 31; + if (blk * 128 >= K) return; + const long long k = blk * 128 + 4 * lane, at = (long long)blockIdx.y * K + k; + float v[4]; +#pragma unroll + for (int j = 0; j < 4; ++j) v[j] = load(x, x_kind, at + j) * __half2float(suh[k + j]); + fwht128(v, lane); +#pragma unroll + for (int j = 0; j < 4; ++j) xh[at + j] = __float2half_rn(opaque(v[j] * kHadScale)); +} + +#define TF_EXL3_LINEAR(K2_, WK_) \ + extern "C" __global__ void __launch_bounds__(WK_ * 32) \ + tf_exl3_linear_k##K2_##_w##WK_(const __half* xh, const uint32_t* T, long long stride_k, long long stride_nb, \ + const __half* svh, void* y, int y_kind, int M, int K, int N) { \ + linear_body(xh, T, stride_k, stride_nb, svh, y, y_kind, M, K, N); \ + } +TF_EXL3_LINEAR(4, 4) +TF_EXL3_LINEAR(4, 8) +TF_EXL3_LINEAR(6, 4) +TF_EXL3_LINEAR(6, 8) +TF_EXL3_LINEAR(8, 4) +TF_EXL3_LINEAR(8, 8) +TF_EXL3_LINEAR(10, 4) +TF_EXL3_LINEAR(10, 8) +TF_EXL3_LINEAR(12, 4) +TF_EXL3_LINEAR(12, 8) +TF_EXL3_LINEAR(16, 4) +TF_EXL3_LINEAR(16, 8) +#undef TF_EXL3_LINEAR diff --git a/zig/src/core/contract/hip_records.zig b/zig/src/core/contract/hip_records.zig index a6e23c8ece4..8165561207e 100644 --- a/zig/src/core/contract/hip_records.zig +++ b/zig/src/core/contract/hip_records.zig @@ -493,7 +493,7 @@ const own_records = [own_count]Record{ .{ .vgprs = 36, .sgprs = 32, .lds = 50688, .private = 0, .bound = 1024, .wave = 32 }, }, }, -} ++ @import("hip_records_pair.zig").records ++ @import("hip_records_prompt.zig").records ++ @import("hip_records_draft.zig").records ++ +} ++ @import("hip_records_pair.zig").records ++ @import("hip_records_prompt.zig").records ++ @import("hip_records_draft.zig").records ++ @import("hip_records_exl3.zig").records ++ @import("hip_records_score.zig").records ++ @import("hip_records_embed.zig").records ++ @import("hip_records_tail.zig").records ++ @import("hip_records_tap.zig").records ++ @import("hip_records_sparse.zig").records; pub const records = own_records ++ @import("hip_records_stream.zig").records ++ @import("hip_records_router.zig").records ++ diff --git a/zig/src/core/contract/hip_records_exl3.zig b/zig/src/core/contract/hip_records_exl3.zig new file mode 100644 index 00000000000..bb3d3f48f57 --- /dev/null +++ b/zig/src/core/contract/hip_records_exl3.zig @@ -0,0 +1,43 @@ +//! Gate 5's records of EXL3's decode-row kernels (exl3.hip's tf_exl3_rot_in and tf_exl3_linear_k*_w*). +const std = @import("std"); +const limits = @import("limits.zig"); +const Record = @import("hip_records.zig").Record; + +const U = limits.HipUsage; + +/// An exl3.hip launch and its (VGPRs, SGPRs, LDS bytes) on each chip, wave32 with no scratch. +fn launch(comptime symbol: []const u8, threads: u32, dynamic: u32, u: [limits.rdna.len][3]u32) Record { + var usage: [limits.rdna.len]U = undefined; + for (&usage, u) |*x, v| x.* = .{ .vgprs = v[0], .sgprs = v[1], .lds = v[2], .bound = threads }; + const l: limits.HipLaunch = .{ + .name = "exl3 " ++ symbol, + .symbol = symbol, + .image = "exl3", + .threads = threads, + .dynamic = dynamic, + }; + return .{ .launch = l, .usage = usage }; +} + +/// The linear at `k2` half-bits and `wk` waves, its waves' sums for 8 rows in dynamic LDS: (VGPRs, SGPRs) a chip. +fn linear(comptime k2: u32, comptime wk: u32, u: [limits.rdna.len][2]u32) Record { + var with: [limits.rdna.len][3]u32 = undefined; + for (&with, u) |*x, v| x.* = .{ v[0], v[1], wk * k2 * 128 }; + return launch(std.fmt.comptimePrint("tf_exl3_linear_k{d}_w{d}", .{ k2, wk }), wk * 32, wk * 8 * 128 * 4, with); +} + +pub const records = [_]Record{ + launch("tf_exl3_rot_in", 128, 0, .{ .{ 16, 12, 0 }, .{ 16, 18, 0 }, .{ 16, 10, 0 }, .{ 16, 9, 0 } }), + linear(4, 4, .{ .{ 206, 45 }, .{ 205, 45 }, .{ 205, 45 }, .{ 205, 46 } }), + linear(4, 8, .{ .{ 214, 43 }, .{ 213, 43 }, .{ 213, 43 }, .{ 213, 44 } }), + linear(6, 4, .{ .{ 209, 45 }, .{ 208, 45 }, .{ 208, 45 }, .{ 208, 46 } }), + linear(6, 8, .{ .{ 217, 43 }, .{ 216, 43 }, .{ 216, 43 }, .{ 216, 44 } }), + linear(8, 4, .{ .{ 209, 45 }, .{ 208, 45 }, .{ 208, 45 }, .{ 208, 46 } }), + linear(8, 8, .{ .{ 217, 43 }, .{ 216, 43 }, .{ 216, 43 }, .{ 216, 44 } }), + linear(10, 4, .{ .{ 213, 45 }, .{ 212, 45 }, .{ 212, 45 }, .{ 212, 46 } }), + linear(10, 8, .{ .{ 221, 43 }, .{ 220, 43 }, .{ 220, 43 }, .{ 220, 44 } }), + linear(12, 4, .{ .{ 214, 45 }, .{ 213, 45 }, .{ 213, 45 }, .{ 213, 46 } }), + linear(12, 8, .{ .{ 222, 43 }, .{ 221, 43 }, .{ 221, 43 }, .{ 221, 44 } }), + linear(16, 4, .{ .{ 219, 45 }, .{ 218, 45 }, .{ 218, 45 }, .{ 218, 46 } }), + linear(16, 8, .{ .{ 227, 43 }, .{ 226, 43 }, .{ 226, 43 }, .{ 226, 44 } }), +}; diff --git a/zig/src/core/contract/hip_records_families.zig b/zig/src/core/contract/hip_records_families.zig index 3e37edecb4b..6db017bdc6e 100644 --- a/zig/src/core/contract/hip_records_families.zig +++ b/zig/src/core/contract/hip_records_families.zig @@ -24,6 +24,7 @@ test "HIP record counts stay pinned in their owning files" { @import("hip_records_dense_text.zig").records.len, @import("hip_records_draft.zig").records.len, @import("hip_records_embed.zig").records.len, + @import("hip_records_exl3.zig").records.len, @import("hip_records_gdn.zig").records.len, @import("hip_records_glm_ocr.zig").records.len, @import("hip_records_item.zig").records.len, diff --git a/zig/src/families/qwen3_5/backend/hip/draft/context.zig b/zig/src/families/qwen3_5/backend/hip/draft/context.zig index 8f2074f0020..a0a7e729034 100644 --- a/zig/src/families/qwen3_5/backend/hip/draft/context.zig +++ b/zig/src/families/qwen3_5/backend/hip/draft/context.zig @@ -25,12 +25,13 @@ pub const Ctx = struct { /// The rows an absorb runs: target rows [start, start + n). pub const Span = struct { start: u64, n: usize }; -/// Where an absorb of rows [start, start + n) lands: a rewind or a gap moves the span, past `window` rows are dropped. +/// Where an absorb of rows [start, start + n) lands: a rewind or a gap moves the context, past `window` rows dropped. pub fn open(ctx: *Ctx, start_: u64, n_: usize, window: usize) Span { var start = start_; var n = n_; if (start < ctx.end) ctx.end = start; - if (start > ctx.end) ctx.begin = start; // a gap (a prompt restored from a cache): the context starts here + // a gap (a prompt restored from a cache) or a rewind below the begin: the context starts here + if (start > ctx.end or start < ctx.begin) ctx.begin = start; if (n > window) { start += n - window; n = window; @@ -99,6 +100,23 @@ test "an absorb past the window keeps its last rows; a rewind and a gap move the try std.testing.expectEqual(@as(u64, 503), ctx.end); } +test "a rewind below the context's begin starts the context at the absorb" { + var ctx: Ctx = .{ .ring = 1 }; + close(&ctx, open(&ctx, 0, 100, 64), 64); + try std.testing.expectEqual(@as(u64, 36), ctx.begin); + // rows from 20 replace everything after them, and the ring holds nothing before them + close(&ctx, open(&ctx, 20, 3, 64), 64); + try std.testing.expectEqual(@as(u64, 20), ctx.begin); + try std.testing.expectEqual(@as(u64, 23), ctx.end); + var ids: [4]u32 = undefined; + var pos: [4]i32 = undefined; + var segs: [1]Segment = undefined; + const shape: Shape = .{ .block = 4, .vocab = 100, .mask = 99 }; + const item = [_]dr.Hold{.{ .stream = undefined, .pending = 7, .position = 24, .depth = 3 }}; + try stage(shape, &item, &.{&ctx}, &ids, &pos, &segs); + try std.testing.expectEqual(Segment{ .ring = 1, .begin = 20, .position = 23 }, segs[0]); +} + test "a frame stages each stream's pending token, its masks, positions from its end and its segment" { var a: Ctx = .{ .ring = 1000, .begin = 2, .end = 10 }; var b: Ctx = .{ .ring = 2000, .begin = 0, .end = 4 }; diff --git a/zig/src/families/qwen3_5/backend/hip/draft/draft.zig b/zig/src/families/qwen3_5/backend/hip/draft/draft.zig index 01fdfe361f8..22ee73c1442 100644 --- a/zig/src/families/qwen3_5/backend/hip/draft/draft.zig +++ b/zig/src/families/qwen3_5/backend/hip/draft/draft.zig @@ -408,6 +408,8 @@ pub fn absorbStart(it: dr.Absorb, row_bytes: usize, dtype: lanes.backend.Feature if (f.space != .device or f.dtype != dtype or f.row_bytes != row_bytes) return error.UnsupportedFeatures; // hip_lanes.zig's features put their first row's position in `offset`: rows of another position are refused if (f.offset != it.start) return error.FeaturesNotAtStart; + // kept rows index the features' rows: one past them would read a ring row the target did not hand over + if (it.rows) |rs| for (rs) |r| if (r >= f.rows) return error.BadDraftRows; return it.start; } @@ -437,6 +439,16 @@ test "an absorb starts at its own start, and refuses features whose first row is try std.testing.expectError(error.UnsupportedFeatures, absorbStart(it, 128, .bf16)); } +test "an absorb's kept rows pick from its features' rows; a row past them is refused" { + const f: lanes.backend.Features = .{ .buffer = 0x1000, .offset = 40, .rows = 16, .row_bytes = 64, .space = .device, .dtype = .bf16 }; + var it: dr.Absorb = .{ .stream = undefined, .features = f, .start = 40, .follow = &.{}, .rows = &.{ 0, 5, 10, 15 } }; + try std.testing.expectEqual(@as(u64, 40), try absorbStart(it, 64, .bf16)); + it.rows = &.{ 0, 16 }; + try std.testing.expectError(error.BadDraftRows, absorbStart(it, 64, .bf16)); + it.features.rows = 17; + try std.testing.expectEqual(@as(u64, 40), try absorbStart(it, 64, .bf16)); +} + test "16-bit logits widen by their kind" { var out: [2]f32 = undefined; widen(.bf16, &.{ 0x3f80, 0xc000 }, &out); 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 index 04dbc827ba5..d72db1959ae 100644 --- a/zig/src/families/qwen3_5/backend/hip/engine/hip_lanes.zig +++ b/zig/src/families/qwen3_5/backend/hip/engine/hip_lanes.zig @@ -4,7 +4,8 @@ const std = @import("std"); const hip = @import("hip"); const lanes = @import("lanes"); const serve = @import("hip_serve"); -const Engine = @import("engine.zig").Engine; +const engine = @import("engine.zig"); +const Engine = engine.Engine; const state = @import("../forward/state.zig"); const mtp = @import("mtp.zig"); const costs = @import("hip_costs.zig"); @@ -69,6 +70,8 @@ pub const Lane = struct { held_n: usize = 0, /// Slots written and kept: the next window starts here. len: usize, + /// The first row a pass tapped: a stream resumed from a snapshot has no tap rows below its resume point. + tapped_from: usize = 0, /// The stream's id on every rank. id: u32 = 0, /// The prompt pass in progress, a chunk a call (null once it is in). @@ -310,6 +313,7 @@ pub const Hip = struct { h.e.pool.ids.reserved += need; _ = try lane.caches.grow(h.gpa, prompt.len); s.cached = @intCast(at); + lane.tapped_from = at; const fill = glue.Fill.init(at, plan.marks); lane.fill = fill; // the other ranks get the stream's pages and where it resumed and cuts @@ -479,19 +483,26 @@ pub const Hip = struct { /// A drafter's tapped layers, told before any stream exists: their rings then come with every stream's caches. pub fn prepareFeatures(h: *Hip, taps: []const u32) !void { - if (h.streams.map.count() != 0) return error.TapsAfterStreams; if (h.e.o.world != 1) return error.TapsUnderTensorParallel; + // the taps the memory plan sized the rings for (native.zig sets them before sizing): kept as they are + const t = &h.e.model().taps; + if (taps.len > 0 and std.mem.eql(u32, taps, t.layers[0..t.n])) return; + if (h.streams.map.count() != 0) return error.TapsAfterStreams; try h.e.setTaps(taps); } - /// Rows [start, start + count) of a lane's tap ring (row = position % ring rows), the newest ring rows kept. + /// Rows [start, start + count) of a lane's tap ring (row = position % ring rows), as far as the ring holds them. pub fn features(h: *Hip, lane: *const Lane, taps: []const u32, start: u64, count: u32) !be.Features { const t = &h.e.model().taps; if (taps.len != t.n or !std.mem.eql(u32, taps, t.layers[0..t.n])) return error.TapsMismatch; const ring = lane.caches.tap orelse return error.NoTaps; // a verify's rows are in the ring before its keep: they count as written until the keep drops them const written = lane.len + if (lane.pending) |p| p.rows else 0; - if (start + count > written or start + count <= written -| t.rows) return error.RowsNotHeld; + const end = start + count; + // a resumed lane's ring holds zeros below its resume point: the snapshot keeps no tap rows + if (count == 0 or start < lane.tapped_from or end > written) return error.RowsNotHeld; + // the drafter reads a span's newest tap_window rows at most: those must not be overwritten yet + if (@max(start, end -| engine.tap_window) < written -| t.rows) return error.RowsNotHeld; const row_bytes = t.n * h.e.model().spec.hidden * 2; return .{ .buffer = ring.base(), .offset = start, .rows = count, .row_bytes = @intCast(row_bytes), .space = .device, .device = h.e.o.device, .dtype = if (h.e.act == .bf16) .bf16 else .f16 }; } diff --git a/zig/src/families/qwen3_5/backend/hip/engine/hip_prompt_test.zig b/zig/src/families/qwen3_5/backend/hip/engine/hip_prompt_test.zig index 3b57dee3797..97ee66c39a3 100644 --- a/zig/src/families/qwen3_5/backend/hip/engine/hip_prompt_test.zig +++ b/zig/src/families/qwen3_5/backend/hip/engine/hip_prompt_test.zig @@ -393,3 +393,37 @@ test "readouts are refused under tensor parallelism and reported on one rank" { try h.useReadout(r); try T.expectEqual(@as(u32, 16384), h.readouts().?.max_rows); } + +test "a resumed lane's features start at its resume point; a fresh lane's at row 0" { + var bridge: @import("../model/bridge.zig").Bridge = undefined; + bridge.model.taps = .{ .n = 2, .rows = 2064 }; + bridge.model.taps.layers[0..2].* = .{ 5, 19 }; + bridge.model.spec.hidden = 8; + var e: @import("engine.zig").Engine = undefined; + e.o = .{}; + e.act = .bf16; + e.bridge = &bridge; + var h: source.Hip = undefined; + h.e = &e; + var ring: [1]u8 = undefined; + var lane: source.Lane = undefined; + lane.caches.tap = .{ .r = undefined, .ptr = &ring, .len = ring.len }; + lane.len = 200; // a 200-row prompt, every row still in the ring + lane.pending = null; + const taps = [_]u32{ 5, 19 }; + lane.tapped_from = 0; + try T.expectEqual(@as(u32, 16), (try h.features(&lane, &taps, 0, 16)).rows); + try T.expectError(error.RowsNotHeld, h.features(&lane, &taps, 196, 5)); // its last row is not written + // resumed at row 64: the ring holds zeros below it, which no pass tapped + lane.tapped_from = 64; + const f = try h.features(&lane, &taps, 64, 136); + try T.expectEqual(@as(u64, 64), f.offset); + try T.expectEqual(@as(u32, 136), f.rows); + const refused = [_][2]u64{ + .{ 63, 1 }, // the row before the resume point + .{ 0, 16 }, // rows all below it + .{ 60, 8 }, // rows across it + .{ 196, 5 }, // its last row is not written + }; + for (refused) |r| try T.expectError(error.RowsNotHeld, h.features(&lane, &taps, r[0], @intCast(r[1]))); +} diff --git a/zig/src/families/qwen3_5/backend/hip/engine/native.zig b/zig/src/families/qwen3_5/backend/hip/engine/native.zig index 9b3467cfd59..5043faff2b8 100644 --- a/zig/src/families/qwen3_5/backend/hip/engine/native.zig +++ b/zig/src/families/qwen3_5/backend/hip/engine/native.zig @@ -14,6 +14,8 @@ const worker = @import("worker.zig"); const hip_lanes = @import("hip_lanes.zig"); const joint = @import("joint_readout.zig"); const config = @import("../../../weights/config.zig"); +const draft = @import("../draft/draft.zig"); +const Draft = draft.Draft; /// The MLX affine widths this native text server loads, each with its group size. const mlx_formats = blk: { @@ -39,6 +41,8 @@ pub fn Native(comptime type_name: []const u8) type { pub const prefill_step: u32 = 0; pub const open = openEngine; pub const follow = followRank; + /// --drafter loads a DFlash2 draft model over the dense checkpoints (Qwen3.8-27B's); the sparse ones take none. + pub const takes_drafter = std.mem.eql(u8, type_name, "qwen3_5"); }; } @@ -58,6 +62,8 @@ pub const Loaded = struct { startup: []const u8, /// The readouts the engine answers, if any (then it generates no text); the host's defaults otherwise. offer: serve.Offer = .{}, + /// The DFlash2 drafter --drafter loaded, its taps already filling the streams' rings (null: none). + drafter: ?lanes.drafter.Drafter = null, }; /// A flag or a resource the engine cannot take: `problem` says why. @@ -94,6 +100,18 @@ fn oneRank(a: std.mem.Allocator, io: std.Io, dir: []const u8, o: Options) ?[]con return "the joint schema head serves on one rank; drop --tp"; } +const bf16_drafter = "--drafter: the HIP engine runs its DFlash2 drafter over quantized checkpoints only; " ++ + "serve this BF16 checkpoint without --drafter"; + +/// Why --drafter cannot run over `dir`: the drafter's rounds are priced by timed windows, which BF16 targets skip. +fn bf16Drafter(gpa: std.mem.Allocator, io: std.Io, dir: []const u8, o: Options) ?[]const u8 { + if (o.drafter == null) return null; + // a config that does not read is the loader's to report + var c = config.Config.read(gpa, io, dir) catch return null; + defer c.deinit(); + return if (c.quant == .bf16) bf16_drafter else null; +} + /// A bf16 checkpoint's joint schema head on the device (null for every other checkpoint); refused by name. fn loadJoint(a: std.mem.Allocator, gpa: std.mem.Allocator, io: std.Io, e: *Engine, dir: []const u8, problem: *[]const u8) Refused!?joint.Loaded { if (!e.plain() or !joint.present(io, a, dir)) return null; @@ -116,13 +134,28 @@ const Prepared = struct { /// A Clef checkpoint's head weights and the readouts it plans (null for every other checkpoint). joint: ?joint.Loaded = null, bounds: hip.joint_schema.plan.Bounds = undefined, + draft: ?*Draft = null, }; /// Device bytes of `streams` lanes at `capacity` beside the weights, and their readout states and the head's scratch. -fn served(e: *Engine, streams: usize, capacity: usize, readouts: ?Readouts) !usize { +fn served(e: *Engine, d: ?*Draft, streams: usize, capacity: usize, readouts: ?Readouts) !usize { const rows = streams * hip_lanes.Hip.max_window; + // a drafter's tap rings hold its window past the rows a forward writes: sized for these streams' rows + if (d != null) { + e.o.batch_rows = rows; + try e.setTaps(d.?.c.tapLayers()); + } + const drafts = if (d) |x| streams * x.streamBytes() else 0; const head = if (readouts) |r| hip.joint_schema.plan.bytes(r.cfg, r.bounds, streams) else 0; - return try e.planBytes(streams, rows, capacity, streams * pages.pagesFor(capacity) + pages.pagesFor(rows), 0) + head; + return drafts + try e.planBytes(streams, rows, capacity, streams * pages.pagesFor(capacity) + pages.pagesFor(rows), 0) + head; +} + +/// The DFlash2 drafter in `dir` on `e`, its taps set before the streams are sized, frames of up to `streams`. +fn openDraft(gpa: std.mem.Allocator, io: std.Io, e: *Engine, dir: []const u8, streams: usize) !*Draft { + const c = try draft.config.Config.read(gpa, io, dir, draft.config.Target.of(e.model().spec)); + try e.setTaps(c.tapLayers()); + errdefer e.setTaps(&.{}) catch {}; + return Draft.init(gpa, io, e, dir, @min(@max(streams, 1), draft.max_streams)); } const Readouts = struct { cfg: @import("core").joint_schema.Config, bounds: hip.joint_schema.plan.Bounds }; @@ -204,6 +237,14 @@ fn prepare( // a Clef head's weights go up beside the model's and count with them var head = try loadJoint(a, gpa, io, e, dir, problem); errdefer if (head) |*h| h.deinit(); + // the drafter's weights and scratch count with the model's; each stream's context with the streams' + const d: ?*Draft = if (o.drafter) |dir_d| openDraft(gpa, io, e, dir_d, o.streams) catch |err| return steps.refuseAll( + a, + problem, + "the native HIP engine cannot load the drafter {s} ({s})", + .{ dir_d, @errorName(err) }, + ) else null; + errdefer if (d) |x| x.deinit(); const model = hip.usage(false).device - held; const after = e.budget(io) catch |err| return steps.refuseAll( a, @@ -220,7 +261,7 @@ fn prepare( // 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, readouts) catch |err| return steps.refuseAll( + if ((served(e, d, streams, capacity, readouts) catch |err| return steps.refuseAll( a, problem, "the native HIP engine cannot count its scratch ({s})", @@ -230,11 +271,11 @@ fn prepare( streams = (try steps.together(a, .{ streams, 0 }, .least, problem))[0]; // every rank holds the same least, so every rank refuses here alike if (streams == 0) { - const one = served(e, 1, capacity, readouts) catch 0; + const one = served(e, d, 1, capacity, readouts) 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", .{ window, gibs(one), gibs(room), gibs(model), gibs(reserve) }); } if (streams < o.streams and o.fixed) { - const asked = served(e, o.streams, capacity, readouts) catch 0; + const asked = served(e, d, o.streams, capacity, readouts) catch 0; return steps.refuseAll( a, problem, @@ -243,7 +284,7 @@ fn prepare( .{ o.streams, gibs(asked), window, gibs(room), streams }, ); } - const need = served(e, streams, capacity, readouts) catch |err| return steps.refuseAll( + const need = served(e, d, streams, capacity, readouts) catch |err| return steps.refuseAll( a, problem, "the native HIP engine cannot count its scratch ({s})", @@ -276,11 +317,18 @@ fn prepare( "the native HIP engine cannot allocate its scratch and pages ({s})", .{@errorName(err)}, ); - const lane = gibs(state.Caches.deviceBytes(e.model(), capacity) + e.model().taps.ringBytes(e.model().spec.hidden) + 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, window, gibs(room), gibs(reserve), gibs(budget), cache.pages, cache.snaps, prefix.chunk, + if (d) |x| x.reserve(streams) catch |err| return steps.refuseAll( + a, + problem, + "the drafter cannot allocate its streams' contexts ({s})", + .{@errorName(err)}, + ); + const own_bytes = if (d) |x| x.streamBytes() else 0; + const lane = gibs(state.Caches.deviceBytes(e.model(), capacity) + e.model().taps.ringBytes(e.model().spec.hidden) + pages.pagesFor(capacity) * memory.pageBytes(e.weights.spec, e.act.size()) + own_bytes); + const startup = try std.fmt.allocPrint(gpa, "HIP {s} device {d}, rank {d} of {d}: model {d:.2} GiB{s}; {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), if (d != null) " with its DFlash2 drafter" else "", streams, if (streams == 1) "" else "s", lane, window, gibs(room), gibs(reserve), gibs(budget), cache.pages, cache.snaps, prefix.chunk, }); - return .{ .e = e, .streams = streams, .cache = cache, .startup = startup, .joint = head, .bounds = if (readouts) |r| r.bounds else undefined }; + return .{ .e = e, .streams = streams, .cache = cache, .startup = startup, .joint = head, .bounds = if (readouts) |r| r.bounds else undefined, .draft = d }; } const Owned = struct { @@ -289,6 +337,7 @@ const Owned = struct { backend: *hip_lanes.Hip, startup: []const u8, joint: ?*joint.Joint = null, + draft: ?*Draft, }; fn release(p: *anyopaque) void { @@ -299,6 +348,7 @@ fn release(p: *anyopaque) void { j.deinit(); own.gpa.destroy(j); } + if (own.draft) |d| d.deinit(); own.e.deinit(); own.gpa.free(own.startup); own.gpa.destroy(own); @@ -306,10 +356,11 @@ fn release(p: *anyopaque) void { /// 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 { - if (decisionOnly(a, gpa, io, dir) orelse oneRank(a, io, dir, o)) |why| return refuse(a, problem, "{s}", .{why}); + if (decisionOnly(a, gpa, io, dir) orelse oneRank(a, io, dir, o) orelse bf16Drafter(gpa, io, dir, o)) |why| return refuse(a, problem, "{s}", .{why}); var steps: hip.Startup = .{ .link = if (dev.group) |g| g.link() else null }; var p = try prepare(a, gpa, io, dev, dir, o, &steps, problem); errdefer p.e.deinit(); + errdefer if (p.draft) |d| d.deinit(); errdefer gpa.free(p.startup); var weights_owned = p.joint != null; errdefer if (weights_owned) p.joint.?.deinit(); @@ -322,7 +373,7 @@ fn openEngine(a: std.mem.Allocator, gpa: std.mem.Allocator, io: std.Io, dev: hip "the native HIP engine cannot start its lanes ({s})", .{@errorName(err)}, ); - own.* = .{ .gpa = gpa, .e = p.e, .backend = backend, .startup = p.startup }; + own.* = .{ .gpa = gpa, .e = p.e, .backend = backend, .startup = p.startup, .draft = p.draft }; 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; @@ -347,6 +398,8 @@ fn openEngine(a: std.mem.Allocator, gpa: std.mem.Allocator, io: std.Io, dev: hip _ = try steps.together(a, .{ 0, 0 }, .first, problem); // a lone rank times its forwards for the depth rule; the ranks of a group draft without costs; bf16 drafts none if (dev.group) |g| own.backend.withLink(g.link()) else if (!p.e.plain()) own.backend.measure(); + // the drafter prices its rounds by the target's windows, timed with the taps on (cuda_native.zig's timeWindows) + if (p.draft) |d| for (own.backend.costs.window[0..own.backend.costs.windows]) |c| d.setCost(c.width, c.ms); return .{ .backend = own.backend.backend(), .facts = own.backend.facts(), @@ -356,6 +409,7 @@ fn openEngine(a: std.mem.Allocator, gpa: std.mem.Allocator, io: std.Io, dev: hip .streams = p.streams, .startup = p.startup, .offer = .{ .readouts = own.backend.readouts(), .vision = serve.vision.offer(p.e.vision) }, + .drafter = if (p.draft) |d| d.drafter() else null, }; } @@ -454,6 +508,29 @@ test "a bf16 checkpoint without a joint head serves chat when the engine reads i try std.testing.expect(decisionOnly(a, std.testing.allocator, io, dir) == null); } +test "--drafter is refused over a BF16 checkpoint before it loads; a quantized one, or no --drafter, is not" { + const io = std.testing.io; + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + const dir = try std.fmt.allocPrint(a, ".zig-cache/tmp/{s}", .{tmp.sub_path}); + // a BF16 checkpoint the engine serves for chat: decisionOnly lets it through, --drafter does not + const bf16 = @embedFile("../../../fixtures/lighton-ocr-0.8b.json"); + try tmp.dir.writeFile(io, .{ .sub_path = "config.json", .data = bf16 }); + const drafted: Options = .{ .window = 64, .streams = 1, .drafter = "/models/drafter" }; + try std.testing.expect(decisionOnly(a, std.testing.allocator, io, dir) == null); + try std.testing.expectEqualStrings(bf16_drafter, bf16Drafter(std.testing.allocator, io, dir, drafted) orelse ""); + try std.testing.expect(bf16Drafter(std.testing.allocator, io, dir, .{ .window = 64, .streams = 1 }) == null); + const affine = "\"image_token_id\": 248056, \"quantization\": {\"group_size\": 64, \"bits\": 4, \"mode\": \"affine\"},"; + const mlx = try std.mem.replaceOwned(u8, a, bf16, "\"image_token_id\": 248056,", affine); + try tmp.dir.writeFile(io, .{ .sub_path = "config.json", .data = mlx }); + var read = try config.Config.read(std.testing.allocator, io, dir); // it reads, so the null below is no read failure + defer read.deinit(); + try std.testing.expect(read.quant != .bf16 and bf16Drafter(std.testing.allocator, io, dir, drafted) == null); +} + test "capability audit: HIP Qwen format names cover the admitted affine widths" { var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); defer arena.deinit(); diff --git a/zig/src/hip/kernel_tests.zig b/zig/src/hip/kernel_tests.zig index 11c8b4329f6..d8573084e81 100644 --- a/zig/src/hip/kernel_tests.zig +++ b/zig/src/hip/kernel_tests.zig @@ -58,6 +58,7 @@ test { _ = @import("kernel_tests/stats.zig"); _ = @import("kernel_tests/tap.zig"); _ = @import("kernel_tests/draft.zig"); + _ = @import("kernel_tests/exl3.zig"); _ = @import("kernel_tests/ops.zig"); _ = @import("kernel_tests/conv_split.zig"); _ = @import("kernel_tests/dense.zig"); diff --git a/zig/src/hip/kernel_tests/exl3.zig b/zig/src/hip/kernel_tests/exl3.zig new file mode 100644 index 00000000000..51695281b08 --- /dev/null +++ b/zig/src/hip/kernel_tests/exl3.zig @@ -0,0 +1,295 @@ +//! EXL3's decode-row kernels: weights decoded bit for bit, a row's bits in any window, the rotation by its fp32 steps. +const std = @import("std"); +const core = @import("core"); +const rig = @import("rig.zig"); +const exl3 = @import("../launches/exl3.zig"); +const fmt = core.exl3_format; +const Rig = rig.Rig; +const gpa = rig.gpa; +const at = rig.at; + +const had: f32 = 0.08838834764831845; + +/// The kernels' unscaled 128-point butterfly in fp32: stages 1 to 64 apart, a + b low and a - b high. +fn fwht(v: *[128]f32) void { + var d: usize = 1; + while (d < 128) : (d *= 2) { + var base: usize = 0; + while (base < 128) : (base += 2 * d) for (0..d) |j| { + const a = v[base + j]; + const b = v[base + j + d]; + v[base + j] = a + b; + v[base + j + d] = a - b; + }; + } +} + +/// Random trellis words in the checkpoint's layout, [K/16, N/16, tile words]. +fn randomTrellis(rng: *rig.Rng, w: fmt.Width, k: usize, n: usize) ![]i16 { + const tr = try gpa.alloc(i16, (k / 16) * (n / 16) * w.tileWords()); + for (tr) |*v| v.* = @bitCast(@as(u16, @truncate(rng.next()))); + return tr; +} + +/// A search for a tile's stream whose 256 values all decode above zero, or all below: a value's bits at a time. +const Search = struct { + rng: *rig.Rng, + neg: bool, + /// Stream bits a value adds (a whole width's half-bits), and the ring's length. + g: usize, + ring: usize, + bits: [128 * 16]u1 = undefined, + budget: usize = 0, + + /// The 16-bit window ending at `end` decodes to a value of the wanted sign. + fn signed(s: *const Search, end: usize) bool { + var state: u16 = 0; + for (0..16) |b| state = (state << 1) | s.bits[(end + s.ring - 16 + b) % s.ring]; + const v = fmt.codebookValue(.mul1, state); + return if (s.neg) v < 0 else v > 0; + } + + fn from(s: *Search, p: usize) bool { + if (s.budget == 0) return false; + s.budget -= 1; + // the windows that wrap past the stream's start are whole once every bit is set + if (p == 256) { + var q: usize = 0; + while ((q + 1) * s.g < 16) : (q += 1) if (!s.signed((q + 1) * s.g)) return false; + return true; + } + const options = @as(usize, 1) << @intCast(s.g); + const first: usize = @intCast(s.rng.next() % options); + for (0..options) |i| { + const v = (first + i) % options; + for (0..s.g) |b| s.bits[p * s.g + b] = @intCast((v >> @intCast(s.g - 1 - b)) & 1); + const end = (p + 1) * s.g; + if ((end < 16 or s.signed(end)) and s.from(p + 1)) return true; + } + return false; + } +}; + +/// A tile's words (checkpoint order: MSB-first bits in little-endian int16 pairs) whose values all have one sign. +fn signedTile(rng: *rig.Rng, w: fmt.Width, neg: bool, words: []i16) void { + var s: Search = .{ .rng = rng, .neg = neg, .g = w.halves / 2, .ring = 128 * @as(usize, w.halves) }; + while (true) { + s.budget = 100_000; + if (s.from(0)) break; + } + var word: [64]u32 = @splat(0); + for (0..s.ring) |i| word[i / 32] |= @as(u32, s.bits[i]) << @intCast(31 - i % 32); + for (0..s.ring / 32) |j| { + words[2 * j] = @bitCast(@as(u16, @truncate(word[j]))); + words[2 * j + 1] = @bitCast(@as(u16, @truncate(word[j] >> 16))); + } +} + +/// [K/16, N/16, tile words] from a pool of 16 one-signed tiles, a tile picked by its position. +fn signedTrellis(rng: *rig.Rng, w: fmt.Width, neg: bool, k: usize, n: usize) ![]i16 { + const words = w.tileWords(); + var pool: [16 * 128]i16 = undefined; + for (0..16) |i| signedTile(rng, w, neg, pool[i * words ..][0..words]); + const tr = try gpa.alloc(i16, (k / 16) * (n / 16) * words); + for (0..k / 16) |kt| for (0..n / 16) |nt| { + const i = (kt * 7 + nt * 13) % 16; + @memcpy(tr[(kt * (n / 16) + nt) * words ..][0..words], pool[i * words ..][0..words]); + }; + return tr; +} + +/// The same tiles as 128-column strips: strip nb holds its k steps of eight tiles each. +fn strips(w: fmt.Width, stored: []const i16, k: usize, n: usize) ![]i16 { + const words = w.tileWords(); + const out = try gpa.alloc(i16, stored.len); + for (0..n / 128) |nb| for (0..k / 16) |kt| for (0..8) |t| { + const from = (kt * (n / 16) + nb * 8 + t) * words; + const to = ((nb * (k / 16) + kt) * 8 + t) * words; + @memcpy(out[to..][0..words], stored[from..][0..words]); + }; + return out; +} + +/// The checkpoint layout's strides in 32-bit words, or the strips layout's. +fn layout(w: fmt.Width, k: usize, n: usize, as_strips: bool) [2]u64 { + const tw: u64 = w.tileWords() / 2; + return if (as_strips) .{ 8 * tw, (k / 16) * 8 * tw } else .{ (n / 16) * tw, 8 * tw }; +} + +fn randomHalves(rng: *rig.Rng, n: usize) ![]u16 { + const out = try gpa.alloc(u16, n); + for (out) |*v| v.* = rig.f16Bits(rng.unit()); + return out; +} + +// one-signed tiles, so each zero of the identity enters dot2 as +0: x +0 for positive weights, -0 for negative ones +test "the linear decodes every width's weights as exl3_format does, bit for bit, at 4 and 8 waves and both layouts" { + const t = try Rig.open(1 << 20); + defer t.close(); + var rng: rig.Rng = .{ .state = 0xE3D1 }; + // (k, n): 4 waves on the checkpoint layout, 8 waves on strips + const sizes = [_][3]usize{ .{ 256, 256, 0 }, .{ 1024, 8192, 1 } }; + for (sizes) |sz| { + const k = sz[0]; + const n = sz[1]; + try std.testing.expectEqual(@as(u32, if (sz[2] == 1) 8 else 4), exl3.waves(k, n)); + // xh = I: row r is 1.0 at k = r, so y's row r is W's row r, rotated by 128 columns + const xh = try gpa.alloc(u16, k * k); + defer gpa.free(xh); + const ones = try gpa.alloc(u16, n); + defer gpa.free(ones); + @memset(ones, 0x3c00); + var dx = try t.alloc(k * k * 2); + defer dx.free(); + var dsvh = try t.upload(ones); + defer dsvh.free(); + var dy = try t.alloc(k * n * 4); + defer dy.free(); + const wq = try gpa.alloc(f16, k * n); + defer gpa.free(wq); + for (exl3.widths) |halves| for ([_]bool{ false, true }) |neg| { + const w = fmt.Width{ .halves = @intCast(halves) }; + const stored = try signedTrellis(&rng, w, neg, k, n); + defer gpa.free(stored); + fmt.unpack(w, .mul1, stored, k / 16, n / 16, wq); + for (wq) |v| if ((v < 0) != neg) return error.TestUnexpectedResult; + @memset(xh, if (neg) 0x8000 else 0); + for (0..k) |r| xh[r * k + r] = 0x3c00; + try dx.upload(0, std.mem.sliceAsBytes(xh)); + const words = if (sz[2] == 1) try strips(w, stored, k, n) else try gpa.dupe(i16, stored); + defer gpa.free(words); + var dt = try t.upload(words); + defer dt.free(); + const st = layout(w, k, n, sz[2] == 1); + const tr: exl3.Trellis = .{ .words = at(dt), .halves = halves, .stride_k = st[0], .stride_nb = st[1] }; + try exl3.linear(&t.on, at(dx), tr, at(dsvh), at(dy), 0, k, k, n, t.stream.handle); + try t.stream.synchronize(); + const got = try rig.download(f32, dy); + defer gpa.free(got); + for (0..k) |r| for (0..n / 128) |b| { + var v: [128]f32 = undefined; + for (&v, 0..) |*e, q| e.* = wq[r * n + b * 128 + q]; + fwht(&v); + for (v, 0..) |e, q| { + const want: u32 = @bitCast(e * had * 1.0); + const have: u32 = @bitCast(got[r * n + b * 128 + q]); + if (want != have) { + const at_ = .{ halves / 2, if (neg) "-" else "+", k, n, r, b * 128 + q, have, want }; + std.debug.print("{d}-bit {s} k {d} n {d}: row {d} column {d} is {x} where {x}\n", at_); + return error.TestUnexpectedResult; + } + } + }; + }; + } +} + +test "a row's outputs are the same bits alone, in any window and in every pass of 16 rows" { + const t = try Rig.open(1 << 20); + defer t.close(); + var rng: rig.Rng = .{ .state = 0xE3D2 }; + const rows = 64; + for ([_][3]usize{ .{ 512, 256, 6 }, .{ 1024, 8192, 10 } }) |sz| { + const k = sz[0]; + const n = sz[1]; + const w = fmt.Width{ .halves = @intCast(sz[2]) }; + const words = try randomTrellis(&rng, w, k, n); + defer gpa.free(words); + const xh = try randomHalves(&rng, rows * k); + defer gpa.free(xh); + const svh = try randomHalves(&rng, n); + defer gpa.free(svh); + var dt = try t.upload(words); + defer dt.free(); + var dx = try t.upload(xh); + defer dx.free(); + var dsvh = try t.upload(svh); + defer dsvh.free(); + var dall = try t.alloc(rows * n * 4); + defer dall.free(); + var dw = try t.alloc(rows * n * 4); + defer dw.free(); + const st = layout(w, k, n, false); + const tr: exl3.Trellis = .{ .words = at(dt), .halves = w.halves, .stride_k = st[0], .stride_nb = st[1] }; + try exl3.linear(&t.on, at(dx), tr, at(dsvh), at(dall), 0, rows, k, n, t.stream.handle); + try t.stream.synchronize(); + const all = try rig.download(f32, dall); + defer gpa.free(all); + // (first row, rows): alone, the rows path at 2 to 8, its two parts at 9 to 16, and passes past 16 + const windows = [_][2]usize{ + .{ 0, 1 }, .{ 5, 1 }, .{ 63, 1 }, .{ 0, 2 }, .{ 3, 7 }, + .{ 8, 8 }, .{ 9, 9 }, .{ 0, 16 }, .{ 17, 17 }, .{ 40, 24 }, + }; + for (windows) |win| { + try exl3.linear(&t.on, at(dx) + win[0] * k * 2, tr, at(dsvh), at(dw), 0, win[1], k, n, t.stream.handle); + try t.stream.synchronize(); + const got = try rig.download(f32, dw); + defer gpa.free(got); + const want = std.mem.sliceAsBytes(all[win[0] * n ..][0 .. win[1] * n]); + if (std.mem.indexOfDiff(u8, want, std.mem.sliceAsBytes(got[0 .. win[1] * n]))) |i| { + const at_ = .{ k, n, win[0], win[1], i }; + std.debug.print("k {d} n {d}: rows {d}+{d} differ from the 64-row run at byte {d}\n", at_); + return error.TestUnexpectedResult; + } + } + } +} + +test "rot_in rounds the fp32 butterfly of x * suh to fp16 once, from fp32, fp16 and bf16 rows" { + const t = try Rig.open(1 << 20); + defer t.close(); + var rng: rig.Rng = .{ .state = 0xE3D3 }; + // 391,680 roundings over the three kinds, so the rare fp16 output that a 1-ulp fp32 error moves shows up + const k = 2048 + 128; + const rows = 60; + const suh = try randomHalves(&rng, k); + defer gpa.free(suh); + var dsuh = try t.upload(suh); + defer dsuh.free(); + var dxh = try t.alloc(rows * k * 2); + defer dxh.free(); + const xs = try gpa.alloc(f32, rows * k); + defer gpa.free(xs); + for (xs) |*v| v.* = rng.unit() * 3; + for ([_]c_int{ 0, 1, 2 }) |kind| { + const in = try gpa.alloc(u32, rows * k); + defer gpa.free(in); + const vals = try gpa.alloc(f32, rows * k); + defer gpa.free(vals); + for (xs, in, vals) |v, *b, *e| { + b.* = switch (kind) { + 0 => @bitCast(v), + 1 => rig.f16Bits(v), + else => rig.bf16Bits(v), + }; + e.* = switch (kind) { + 0 => v, + 1 => @floatCast(rig.f16Value(@intCast(b.*))), + else => @floatCast(rig.bf16Value(@intCast(b.*))), + }; + } + var dx = if (kind == 0) try t.upload(in) else blk: { + const narrow = try gpa.alloc(u16, rows * k); + defer gpa.free(narrow); + for (narrow, in) |*a, b| a.* = @intCast(b); + break :blk try t.upload(narrow); + }; + defer dx.free(); + try exl3.rotIn(&t.on, at(dx), kind, at(dsuh), at(dxh), rows, k, t.stream.handle); + try t.stream.synchronize(); + const got = try rig.download(u16, dxh); + defer gpa.free(got); + for (0..rows) |r| for (0..k / 128) |b| { + var v: [128]f32 = undefined; + for (&v, 0..) |*e, q| { + const sc: f32 = @floatCast(rig.f16Value(suh[b * 128 + q])); + e.* = vals[r * k + b * 128 + q] * sc; + } + fwht(&v); + for (v, 0..) |e, q| { + const want: u16 = @bitCast(@as(f16, @floatCast(e * had))); + try std.testing.expectEqual(want, got[r * k + b * 128 + q]); + } + }; + } +} diff --git a/zig/src/hip/kernels.zig b/zig/src/hip/kernels.zig index d18bbe616f6..69ce080ebb0 100644 --- a/zig/src/hip/kernels.zig +++ b/zig/src/hip/kernels.zig @@ -19,6 +19,7 @@ pub const Group = enum { lighton_ocr, qwen_vision, draft, + exl3, }; pub const group_count = @typeInfo(Group).@"enum".field_names.len; diff --git a/zig/src/hip/launches.zig b/zig/src/hip/launches.zig index 3ac0f4ee6c1..2bdad452847 100644 --- a/zig/src/hip/launches.zig +++ b/zig/src/hip/launches.zig @@ -47,6 +47,7 @@ const columns = @import("launches/columns.zig"); const vision = @import("launches/vision.zig"); const dense_text = @import("launches/dense_text.zig"); pub const draft = @import("launches/draft.zig"); +pub const exl3 = @import("launches/exl3.zig"); pub const ConvArgs = conv.ConvArgs; pub const PlanArgs = plan.PlanArgs; @@ -110,6 +111,8 @@ pub const Launcher = struct { nemo: nemotron_moe.Fns, /// The DFlash2 drafter's kernels (draft/draft.hip). draft: draft.Fns, + /// EXL3 projections for decode rows (exl3/exl3.hip). + exl3: exl3.Fns, const PlanFns = struct { kv_write: Function, @@ -331,6 +334,7 @@ pub const Launcher = struct { l.sum_partials = try att.function("tf_sum_partials"); l.mamba = try mamba.Fns.load(l.mods[@backingInt(kernels.Group.mamba)]); l.draft = try draft.Fns.load(l.mods[@backingInt(kernels.Group.draft)]); + l.exl3 = try exl3.Fns.load(l.mods[@backingInt(kernels.Group.exl3)]); const tiles = l.mods[@backingInt(kernels.Group.affine_tiles)]; const dot2 = l.mods[@backingInt(kernels.Group.affine_dot2)]; const chip = caps.Caps.of(kernels.arch) orelse return error.Invalid; diff --git a/zig/src/hip/launches/exl3.zig b/zig/src/hip/launches/exl3.zig new file mode 100644 index 00000000000..704bcebbbfe --- /dev/null +++ b/zig/src/hip/launches/exl3.zig @@ -0,0 +1,117 @@ +//! EXL3 projections for decode rows: the input rotation and the trellis linear (exl3/exl3.hip), mul1 codebook. + +const std = @import("std"); +const Launcher = @import("../launches.zig").Launcher; +const Module = @import("../module.zig").Module; +const Function = @import("../module.zig").Function; +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; + +/// The trellis widths with a linear (half-bits a weight, 2 to 8 bits), and the waves a block splits K over. +pub const widths = [_]u32{ 4, 6, 8, 10, 12, 16 }; +pub const wave_counts = [_]u32{ 4, 8 }; + +pub const Fns = struct { + rot_in: Function, + linear: [widths.len][wave_counts.len]Function, + + pub fn load(m: Module) Error!Fns { + var f: Fns = .{ .rot_in = try m.function("tf_exl3_rot_in"), .linear = undefined }; + inline for (widths, 0..) |k2, i| inline for (wave_counts, 0..) |wk, j| { + f.linear[i][j] = try m.function(std.fmt.comptimePrint("tf_exl3_linear_k{d}_w{d}", .{ k2, wk })); + }; + return f; + } +}; + +/// The index of a trellis width in `widths`, null for one without a linear. +pub fn widthIndex(halves: u32) ?usize { + return std.mem.indexOfScalar(u32, &widths, halves); +} + +/// Whole 128-wide blocks of K and N and at least one row, each within the kernels' int arguments. +pub fn fits(rows: usize, k: usize, n: usize) bool { + const most: usize = std.math.maxInt(c_int); + if (rows == 0 or k == 0 or n == 0 or rows > most or k > most or n > most) return false; + return k % 128 == 0 and n % 128 == 0; +} + +/// CUDA's dense plan without a K split: 8 waves from 64 column blocks when each wave keeps 8 k tiles, else 4. +pub fn waves(k: usize, n: usize) u32 { + return if (n / 128 >= 64 and k / 16 / 8 >= 8) 8 else 4; +} + +/// The linear's LDS for its waves' sums: 128 floats a wave and row, at most 8 rows. +pub fn sharedBytes(wk: u32, rows: usize) u32 { + return wk * @as(u32, @intCast(@min(rows, 8))) * 128 * 4; +} + +/// xh [rows, k] fp16 = (x * suh) H / sqrt(128) by 128-wide blocks, of x [rows, k] (kind 0 fp32, 1 fp16, 2 bf16). +pub fn rotIn(l: *const Launcher, x: u64, x_kind: c_int, suh: u64, xh: u64, rows: usize, k: usize, s: S) Error!void { + if (!fits(rows, k, 128) or x_kind < 0 or x_kind > 2) return invalid("exl3 rot_in"); + var a: Args = .{}; + try a.add(x); + try a.add(x_kind); + try a.add(suh); + try a.add(xh); + try a.add(@as(c_int, @intCast(k))); + try l.go(l.exl3.rot_in, dim(cdiv(k / 128, 4), rows, 1), dim(128, 1, 1), 0, s, &a); +} + +/// A matrix's trellis words: `halves` a weight, tile (kt, nt) at kt stride_k + nt / 8 stride_nb + nt % 8 tile words. +pub const Trellis = struct { words: u64, halves: u32, stride_k: u64, stride_nb: u64 }; + +/// y [rows, n] (kind 0 fp32, 2 bf16) = (xh @ W) H / sqrt(128) * svh by 128-column blocks, W decoded from `t`. +pub fn linear( + l: *const Launcher, + xh: u64, + t: Trellis, + svh: u64, + y: u64, + y_kind: c_int, + rows: usize, + k: usize, + n: usize, + s: S, +) Error!void { + const wi = widthIndex(t.halves) orelse return invalid("exl3 linear width"); + if (!fits(rows, k, n) or (y_kind != 0 and y_kind != 2)) return invalid("exl3 linear"); + const most: u64 = std.math.maxInt(c_longlong); + if (t.stride_k > most or t.stride_nb > most) return invalid("exl3 linear strides"); + const wk = waves(k, n); + var a: Args = .{}; + try a.add(xh); + try a.add(t.words); + try a.add(@as(c_longlong, @intCast(t.stride_k))); + try a.add(@as(c_longlong, @intCast(t.stride_nb))); + try a.add(svh); + try a.add(y); + try a.add(y_kind); + try a.add(@as(c_int, @intCast(rows))); + try a.add(@as(c_int, @intCast(k))); + try a.add(@as(c_int, @intCast(n))); + const f = l.exl3.linear[wi][@intFromBool(wk == 8)]; + try l.go(f, dim(n / 128, 1, 1), dim(wk * 32, 1, 1), sharedBytes(wk, rows), s, &a); +} + +test "exl3 launches: shapes in whole blocks, CUDA's wave counts, and LDS for at most 8 rows" { + try std.testing.expect(fits(1, 5120, 129280) and fits(128, 512, 128)); + try std.testing.expect(!fits(0, 512, 128) and !fits(1, 640 - 64, 128) and !fits(1, 512, 192) and !fits(1, 0, 128)); + try std.testing.expect(!fits(@as(usize, std.math.maxInt(c_int)) + 1, 512, 128)); + try std.testing.expectEqual(@as(u32, 8), waves(5120, 129280)); + try std.testing.expectEqual(@as(u32, 8), waves(6144, 25600)); + try std.testing.expectEqual(@as(u32, 4), waves(512, 128)); + try std.testing.expectEqual(@as(u32, 4), waves(512, 129280)); + try std.testing.expectEqual(@as(u32, 4), waves(5120, 63 * 128)); + try std.testing.expectEqual(@as(u32, 8), waves(1024, 64 * 128)); + try std.testing.expectEqual(@as(u32, 4), waves(1024 - 128, 64 * 128)); + try std.testing.expectEqual(@as(u32, 4 * 128 * 4), sharedBytes(4, 1)); + try std.testing.expectEqual(@as(u32, 8 * 8 * 128 * 4), sharedBytes(8, 64)); + try std.testing.expectEqual(@as(?usize, 5), widthIndex(16)); + try std.testing.expectEqual(@as(?usize, null), widthIndex(14)); +} diff --git a/zig/src/hip_serve/options.zig b/zig/src/hip_serve/options.zig index d277522ef71..e26ef4a1b19 100644 --- a/zig/src/hip_serve/options.zig +++ b/zig/src/hip_serve/options.zig @@ -10,6 +10,8 @@ pub const Options = struct { cache_gib: ?f64 = null, cache_over_cap: bool = false, vision: ?api.VisionOpen = null, + /// --drafter: a DFlash2 draft model's directory (null: none), loaded on a lone rank before the streams are sized. + drafter: ?[]const u8 = null, }; test "HIP native options: existing callers remain text-only and image limits retain explicit overrides" { diff --git a/zig/src/native/hip.zig b/zig/src/native/hip.zig index 344a1319f5d..e4f21fbe270 100644 --- a/zig/src/native/hip.zig +++ b/zig/src/native/hip.zig @@ -14,6 +14,7 @@ const dots = @import("dots_mocr"); const parse = @import("nemotron_parse"); const lighton = @import("lighton_ocr"); const fam = @import("hip_families.zig"); +const hip_drafter = @import("hip_drafter.zig"); const Allocator = std.mem.Allocator; const admission = hip.admission; const modelContext = admission.modelContext; @@ -60,7 +61,7 @@ fn matrixRefused(comptime F: type, policy: hip.Policy, caps: hip.Caps) ?[]const /// The tensor-parallel flags as the Python ROCm server checks them, and the flags this engine cannot take. fn checkGroup(a: Allocator, o: api.Open, problem: *[]const u8) Refused!void { - if (o.drafter != null) return refuse(a, problem, "--drafter: the HIP engine runs no DFlash2 drafter yet; serve without --drafter", .{}); + if (hip_drafter.groupRefusal(a, o)) |why| return refuse(a, problem, "{s}", .{why}); 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 @@ -139,6 +140,7 @@ fn ready(comptime F: type, a: Allocator, gpa: Allocator, io: std.Io, o: api.Open .cache_gib = o.prompt_cache_gib, .cache_over_cap = o.prompt_cache_over_cap, .vision = o.vision, + .drafter = hip_drafter.drafterOf(o), }, .policy_line = policy_line, }; @@ -209,8 +211,8 @@ fn reasoning(comptime F: type) bool { return if (@hasDecl(F, "reasoning")) F.reasoning else true; } -/// The family's refusals before it loads or joins a group (hip_families.zig). -const flagRefused = fam.refused; +/// The family's refusals before it loads or joins a group, then its refusal of --drafter (hip_drafter.zig). +const flagRefused = hip_drafter.flagRefused; /// One loaded model behind the lane host: everything the engine thread reads lives here. const Host = struct { @@ -223,11 +225,13 @@ const Host = struct { clock: lanes.backend.WallClock, core: lanes.Engine, host: api.LaneHost, + drafted: ?*lanes.drafted.Drafted = null, // --drafter: the family's backend behind Drafted (null: as it loaded) fn close(p: *anyopaque) void { const h: *Host = @ptrCast(@alignCast(p)); h.host.stop(); h.core.deinit(); + hip_drafter.release(h.gpa, h.drafted); h.cfg.deinit(h.gpa); h.release(h.family); if (h.group) |g| g.close(h.gpa); @@ -293,6 +297,8 @@ fn openWith(comptime F: type, a: Allocator, gpa: Allocator, io: std.Io, o: api.O else => |x| return x, }; errdefer loaded.deinit(loaded.ctx); + const wrapped = try hip_drafter.attach(a, gpa, loaded, o, problem) orelse return null; + errdefer hip_drafter.release(gpa, wrapped.drafted); const offer = fam.offerOf(loaded); const text = fam.generates(offer); if (fam.textOnly(o, offer)) @@ -304,10 +310,11 @@ fn openWith(comptime F: type, a: Allocator, gpa: Allocator, io: std.Io, o: api.O 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); + h.drafted = wrapped.drafted; + h.cfg = try lanes.Config.init(gpa, wrapped.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()); + h.core = lanes.Engine.init(gpa, &h.cfg, wrapped.backend, h.clock.clock()); errdefer h.core.deinit(); h.host = api.LaneHost.init(gpa, io, &h.core, .{ .benchmark_ranks = if (r.dev.group) |g| @intCast(g.world) else 1, @@ -317,6 +324,7 @@ fn openWith(comptime F: type, a: Allocator, gpa: Allocator, io: std.Io, o: api.O .decode_share = o.decode_share, .policy = offer.policy orelse h.policy_line, .startup = loaded.startup, + .draft_sources = hip_drafter.draftSources(o, wrapped.drafted), .structures = text and loaded.backend.vtable.first_masked != null, .text_generation = text, .embeddings = offer.embeddings, @@ -522,19 +530,17 @@ test "the group flags: one rank source, a supported world, a master past one ran try std.testing.expectError(error.Refused, checkGroup(a, outside, &problem)); } -test "--drafter is refused before any load, on every rank, until the HIP engine runs DFlash2" { +test "--drafter on qwen3_5 passes the group check on one rank; a group, another family refuse it before any load" { var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); defer arena.deinit(); const a = arena.allocator(); var problem: []const u8 = ""; const drafted: api.Open = .{ .dir = "d", .model_type = "qwen3_5", .drafter = "/models/drafter" }; - try std.testing.expectError(error.Refused, checkGroup(a, drafted, &problem)); - try std.testing.expectStringStartsWith(problem, "--drafter: the HIP engine runs no DFlash2 drafter yet"); - var follower = drafted; - follower.tp = 2; - follower.rank = 1; - follower.master = "node0"; + try std.testing.expect(flagRefused(qwen35.native, drafted) == null and flagRefused(qwen35.native_moe, drafted) != null); + try checkGroup(a, drafted, &problem); + const follower: api.Open = .{ .dir = "d", .model_type = "qwen3_5", .drafter = "/models/drafter", .tp = 2, .rank = 1, .master = "node0" }; try std.testing.expectError(error.Refused, checkGroup(a, follower, &problem)); + try std.testing.expectStringStartsWith(problem, "--drafter with --tp 2:"); } test "--kv-cache fp8 is refused by name on HIP; bf16 caches are not" { @@ -562,6 +568,7 @@ test "matrix=on runs only where the matrix-core tiles exist; auto runs everywher test { _ = @import("draft_sources_hip_test.zig"); _ = @import("hip_confidence_test.zig"); + _ = hip_drafter; } test "slide admission: hip refuses before checkpoint or device access" { diff --git a/zig/src/native/hip_drafter.zig b/zig/src/native/hip_drafter.zig new file mode 100644 index 00000000000..2f4f6b8e5aa --- /dev/null +++ b/zig/src/native/hip_drafter.zig @@ -0,0 +1,252 @@ +//! --drafter on the HIP host: its refusals before any load, and the family's DFlash2 drafter behind Drafted. +const std = @import("std"); +const api = @import("engine_api"); +const lanes = @import("lanes"); +const fam = @import("hip_families.zig"); +const Allocator = std.mem.Allocator; + +/// Why --drafter cannot run under tensor parallelism: the drafter and its taps live on one rank. +const tp_refusal = "--drafter with --tp {d}: the HIP engine runs its DFlash2 drafter on one rank; " ++ + "serve with --tp 1, or without --drafter"; +/// Why --drafter-bits 0 is refused: the HIP drafter quantizes its weights to 4 bits. +const bits_refusal = "--drafter-bits {d}: the HIP engine runs the DFlash2 drafter at 4 bits; " ++ + "serve with --drafter-bits 4"; + +/// Why the group cannot take --drafter, on every rank before any load: the drafter runs on one rank at 4 bits. +pub fn groupRefusal(a: Allocator, o: api.Open) ?[]const u8 { + if (o.drafter == null) return null; + if (o.tp > 1) return std.fmt.allocPrint(a, tp_refusal, .{o.tp}) catch tp_refusal; + if (o.drafter_bits != 4) return std.fmt.allocPrint(a, bits_refusal, .{o.drafter_bits}) catch bits_refusal; + return null; +} + +/// Why a HIP family without a DFlash2 drafter refuses --drafter. +fn familyRefusal(comptime F: type) []const u8 { + const what = if (@hasDecl(F, "model_type")) F.model_type ++ " checkpoints load" else "this family loads"; + return "--drafter: " ++ what ++ " no DFlash2 drafter on HIP; serve without --drafter"; +} + +/// The family's refusal of --drafter before it loads: every family but one that declares `takes_drafter`. +fn refused(comptime F: type, o: api.Open) ?[]const u8 { + if (o.drafter != null and !(@hasDecl(F, "takes_drafter") and F.takes_drafter)) return familyRefusal(F); + return null; +} + +/// The family's refusals before it loads or joins a group (hip_families.zig), then its refusal of --drafter. +pub fn flagRefused(comptime F: type, o: api.Open) ?[]const u8 { + return fam.refused(F, o) orelse refused(F, o); +} + +/// The drafter the family loads: --drafter's, none under --no-drafts, which serves the target alone (as on CUDA). +pub fn drafterOf(o: api.Open) ?[]const u8 { + return if (o.drafts) o.drafter else null; +} + +/// The serving line's drafter: the DFlash2 drafter --drafter attached, by the name it was given (as on CUDA). +pub fn draftSources(o: api.Open, drafted: ?*const lanes.drafted.Drafted) api.DraftSources { + if (drafted == null) return .{}; + return .{ .drafter = .{ .kind = "DFlash2", .name = o.drafter_name orelse o.drafter orelse "" } }; +} + +/// What the host serves: the family's backend and facts as it loaded them, or behind Drafted over its drafter. +pub const Served = struct { + backend: lanes.backend.Backend, + facts: lanes.Model, + /// The lane core's wrapper over the family's backend and drafter (null: served as it loaded). + drafted: ?*lanes.drafted.Drafted = null, +}; + +/// `loaded` behind Drafted when it loaded a drafter; null with `problem`, the model freed, when it cannot attach. +pub fn attach(a: Allocator, gpa: Allocator, loaded: anytype, o: api.Open, problem: *[]const u8) Allocator.Error!?Served { + const as_loaded: Served = .{ .backend = loaded.backend, .facts = loaded.facts }; + const d = if (comptime @hasField(@TypeOf(loaded), "drafter")) loaded.drafter orelse return as_loaded else return as_loaded; + // the drafter's taps were set before the streams were sized; the wrapper's prepare keeps them + const x = try gpa.create(lanes.drafted.Drafted); + x.* = lanes.drafted.Drafted.init(gpa, loaded.backend, d) catch |err| { + gpa.destroy(x); + // the message first: a failed print returns through the caller's errdefer, which frees the model once + problem.* = try std.fmt.allocPrint(a, "the drafter {s} cannot attach to this model ({s})", .{ o.drafter orelse "", @errorName(err) }); + loaded.deinit(loaded.ctx); + return null; + }; + return .{ .backend = x.backend(), .facts = x.facts(loaded.facts), .drafted = x }; +} + +/// Frees the wrapper attach made, after the lane core that ran over it; the family frees its drafter. +pub fn release(gpa: Allocator, drafted: ?*lanes.drafted.Drafted) void { + const x = drafted orelse return; + x.deinit(); + gpa.destroy(x); +} + +const qwen35 = @import("qwen3_5"); +const flashnext = @import("flashnext"); +const nemotron = @import("nemotron"); + +/// A family's open as attach takes it: its drafter, if it loaded one, and the free of the whole model. +const Loaded = struct { + backend: lanes.backend.Backend, + facts: lanes.Model, + drafter: ?lanes.drafter.Drafter = null, + ctx: *anyopaque = undefined, + deinit: *const fn (*anyopaque) void = undefined, +}; + +/// A drafter attach only wraps: it gives its taps and facts, and no stream ever reaches the rest. +const Idle = struct { + depth: u32 = 3, + + fn drafter(x: *Idle) lanes.drafter.Drafter { + return .{ .ptr = x, .vtable = &.{ .taps = taps, .facts = facts, .open = open, .absorb = absorb, .hold = hold, .held = held, .release = close } }; + } + fn taps(_: *anyopaque) []const u32 { + return &.{ 5, 19 }; + } + fn facts(ptr: *anyopaque) lanes.drafter.Facts { + return .{ .depth = @as(*Idle, @ptrCast(@alignCast(ptr))).depth, .step_ms = 1 }; + } + fn open(_: *anyopaque, _: *lanes.Stream) anyerror!void { + return error.Unused; + } + fn absorb(_: *anyopaque, _: []const lanes.drafter.Absorb) anyerror!void { + return error.Unused; + } + fn hold(_: *anyopaque, _: []const lanes.drafter.Hold) anyerror!void { + return error.Unused; + } + fn held(_: *anyopaque, _: []const *lanes.Stream, _: []const []u32) anyerror!void { + return error.Unused; + } + fn close(_: *anyopaque, _: *lanes.Stream) void {} + /// A target that refuses the drafter's taps, as Drafted.init's prepare_features may. + fn refuseTaps(_: *anyopaque, _: []const u32) anyerror!void { + return error.TapsMismatch; + } + /// The model's free, counted in the u32 behind `ctx`. + fn free(ctx: *anyopaque) void { + @as(*u32, @ptrCast(@alignCast(ctx))).* += 1; + } +}; + +test "--drafter with --tp > 1 is refused by name, on rank 0 and on the ranks that follow it" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const group: api.Open = .{ .dir = "d", .model_type = "qwen3_5", .drafter = "/models/drafter", .tp = 2, .master = "node0" }; + const tp = "--drafter with --tp 2: the HIP engine runs its DFlash2 drafter on one rank; serve with --tp 1, or without --drafter"; + try std.testing.expectEqualStrings(tp, groupRefusal(a, group) orelse ""); + var follower = group; + follower.rank = 1; + try std.testing.expectEqualStrings(tp, groupRefusal(a, follower) orelse ""); +} + +test "--drafter passes the group check on one rank at 4 bits; --drafter-bits 0 is refused; no --drafter, nothing" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const drafted: api.Open = .{ .dir = "d", .model_type = "qwen3_5", .drafter = "/models/drafter" }; + try std.testing.expect(groupRefusal(a, drafted) == null); + var bf16 = drafted; + bf16.drafter_bits = 0; + const bits = "--drafter-bits 0: the HIP engine runs the DFlash2 drafter at 4 bits; serve with --drafter-bits 4"; + try std.testing.expectEqualStrings(bits, groupRefusal(a, bf16) orelse ""); + try std.testing.expect(groupRefusal(a, .{ .dir = "d", .model_type = "qwen3_5", .tp = 2, .drafter_bits = 0 }) == null); +} + +test "--drafter loads on the dense qwen3_5 family; every other HIP family refuses it by name before it loads" { + const drafted: api.Open = .{ .dir = "d", .model_type = "qwen3_5", .drafter = "/models/drafter" }; + try std.testing.expect(refused(qwen35.native, drafted) == null); + const by_name = .{ + .{ qwen35.native_moe, "--drafter: qwen3_5_moe checkpoints load no DFlash2 drafter on HIP; serve without --drafter" }, + .{ flashnext.native, "--drafter: qwen4_exp checkpoints load no DFlash2 drafter on HIP; serve without --drafter" }, + .{ nemotron.native, "--drafter: nemotron_h checkpoints load no DFlash2 drafter on HIP; serve without --drafter" }, + }; + inline for (by_name) |f| try std.testing.expectEqualStrings(f[1], refused(f[0], drafted) orelse ""); + const plain: api.Open = .{ .dir = "d", .model_type = "m" }; + inline for (.{ qwen35.native, qwen35.native_moe, flashnext.native, nemotron.native }) |F| try std.testing.expect(refused(F, plain) == null); +} + +test "a plain serve and --no-drafts with --drafter load no drafter and serve as loaded; --drafter loads its own" { + const plain: api.Open = .{ .dir = "d", .model_type = "qwen3_5" }; + try std.testing.expect(drafterOf(plain) == null); + var serial = plain; + serial.drafter = "/models/drafter"; + serial.drafts = false; + try std.testing.expect(drafterOf(serial) == null); + try std.testing.expect(refused(qwen35.native, serial) == null); + const drafted: api.Open = .{ .dir = "d", .model_type = "qwen3_5", .drafter = "/models/drafter" }; + try std.testing.expectEqualStrings("/models/drafter", drafterOf(drafted) orelse ""); + var fake: lanes.fake.Fake = .{ .gpa = std.testing.allocator }; + const Bare = struct { backend: lanes.backend.Backend, facts: lanes.Model }; + var problem: []const u8 = ""; + inline for (.{ Bare{ .backend = fake.backend(), .facts = undefined }, Loaded{ .backend = fake.backend(), .facts = undefined } }) |loaded| { + const served = (try attach(std.testing.allocator, std.testing.allocator, loaded, plain, &problem)) orelse return error.TestUnexpectedResult; + try std.testing.expect(served.drafted == null and served.backend.ptr == loaded.backend.ptr); + release(std.testing.allocator, served.drafted); + } +} + +test "a loaded drafter is served behind Drafted over the family's backend, the model kept; release frees the wrapper" { + var fake: lanes.fake.Fake = .{ .gpa = std.testing.allocator }; + var idle: Idle = .{}; + var frees: u32 = 0; + const loaded: Loaded = .{ .backend = fake.backend(), .facts = .{ .exact_width = 8 }, .drafter = idle.drafter(), .ctx = &frees, .deinit = Idle.free }; + const drafted: api.Open = .{ .dir = "d", .model_type = "qwen3_5", .drafter = "/models/drafter" }; + var problem: []const u8 = ""; + const served = (try attach(std.testing.allocator, std.testing.allocator, loaded, drafted, &problem)) orelse return error.TestUnexpectedResult; + defer release(std.testing.allocator, served.drafted); // std.testing.allocator fails the test if the wrapper leaks + const x = served.drafted orelse return error.TestUnexpectedResult; + try std.testing.expect(served.backend.ptr == @as(*anyopaque, x) and x.target.ptr == loaded.backend.ptr); + try std.testing.expect(served.facts.mtp and served.facts.drafts == idle.depth); + try std.testing.expect(frees == 0 and problem.len == 0); +} + +test "a drafter that cannot attach frees the model once and says why; a failed message leaves the free to the caller" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + var fake: lanes.fake.Fake = .{ .gpa = std.testing.allocator }; + var target = fake.backend(); + var refusing = target.vtable.*; + refusing.prepare_features = Idle.refuseTaps; + target.vtable = &refusing; + var idle: Idle = .{}; + var frees: u32 = 0; + const loaded: Loaded = .{ .backend = target, .facts = .{}, .drafter = idle.drafter(), .ctx = &frees, .deinit = Idle.free }; + const drafted: api.Open = .{ .dir = "d", .model_type = "qwen3_5", .drafter = "/models/drafter" }; + var problem: []const u8 = ""; + try std.testing.expect(try attach(arena.allocator(), std.testing.allocator, loaded, drafted, &problem) == null); + try std.testing.expectEqualStrings("the drafter /models/drafter cannot attach to this model (TapsMismatch)", problem); + try std.testing.expectEqual(@as(u32, 1), frees); + frees = 0; + var failing: std.testing.FailingAllocator = .init(arena.allocator(), .{ .fail_index = 0 }); + try std.testing.expectError(error.OutOfMemory, attach(failing.allocator(), std.testing.allocator, loaded, drafted, &problem)); + try std.testing.expectEqual(@as(u32, 0), frees); // the caller's errdefer frees it, once +} + +test "draft sources: HIP names the DFlash2 drafter --drafter attached; without one the line is unchanged" { + const check = @import("draft_sources_check.zig").check; + const present = @import("draft_sources_check.zig").present; + var e: qwen35.engine.Engine = undefined; + var b: qwen35.hip_lanes.Hip = undefined; + b.e = &e; + b.costs = .{}; + b.head = null; + e.o.batch_rows = 16; + e.o.policy.mtp.drafts = 3; + const plain: api.Open = .{ .dir = "d", .model_type = "qwen3_5" }; + var named = plain; + named.drafter = "/cache/drafter"; + try check(b.facts(), draftSources(plain, null).drafter, true, false); + try check(b.facts(), draftSources(named, null).drafter, true, false); + var facts = b.facts(); + facts.mtp = true; // as Drafted.facts marks the target it wraps + facts.speculate = true; + const x = present(*lanes.drafted.Drafted); + const shown = draftSources(named, x).drafter orelse return error.TestUnexpectedResult; + try std.testing.expectEqualStrings("DFlash2", shown.kind); + try std.testing.expectEqualStrings("/cache/drafter", shown.name); + try check(facts, shown, true, false); + named.drafter_name = "z-lab/Qwen3.8-27B-DFlash2"; + const given = draftSources(named, x).drafter orelse return error.TestUnexpectedResult; + try std.testing.expectEqualStrings("z-lab/Qwen3.8-27B-DFlash2", given.name); +} diff --git a/zig/src/server/benchmark.zig b/zig/src/server/benchmark.zig index f0db746d8a8..fafd4f52538 100644 --- a/zig/src/server/benchmark.zig +++ b/zig/src/server/benchmark.zig @@ -304,11 +304,18 @@ const Printer = struct { } }; -const hip_drafter = "the HIP engine runs no DFlash2 drafter yet"; -/// Why a ROCm run refuses a named ``--drafter`` before it starts. -pub const rocm_drafter = "--drafter: " ++ hip_drafter ++ ", so a rocm run takes none; --drafter none runs without it"; +/// The family the HIP engine runs a DFlash2 drafter over: the dense Qwen3.5 checkpoints (Qwen3.8-27B's). +const hip_drafted = "qwen3_5"; +/// Why a ROCm run refuses a named ``--drafter`` on another family before it starts. +pub const rocm_drafter = "--drafter: the HIP engine runs a DFlash2 drafter over dense " ++ hip_drafted ++ + " checkpoints only, so a rocm run of this model takes none; --drafter none runs without it"; -/// The drafter ``--drafter auto`` names: the family's own; none under --serial or on rocm (HIP runs no DFlash2 yet). +/// Whether a ROCm run passes a named drafter to this checkpoint's family. +fn rocmDrafts(config: json.Value) bool { + return std.mem.eql(u8, model.modelType(config) orelse "", hip_drafted); +} + +/// The drafter ``--drafter auto`` names: the family's own; none under --serial or on rocm (a named one only there). pub fn autoDrafter(config: json.Value, backend: []const u8, serial: bool) ?[]const u8 { if (serial or std.mem.eql(u8, backend, "rocm")) return null; return model.knownDrafter(config); @@ -366,7 +373,7 @@ fn run(ctx: *const Context, args: Args) !u8 { } else return fail(ctx, try std.fmt.allocPrint(a, "This build does not serve model_type {s}; tensorfold-native capabilities --json lists what it serves", .{kind})); const auto = std.mem.eql(u8, args.drafter, "auto"); const given = !auto and !std.mem.eql(u8, args.drafter, "none") and args.drafter.len > 0; - if (rocm and given) return fail(ctx, rocm_drafter); + if (rocm and given and !rocmDrafts(config.value)) return fail(ctx, rocm_drafter); // auto passes the family's own drafter only when serve's cache lookup finds it; nothing is downloaded. const known = if (auto) autoDrafter(config.value, backend, args.serial) else null; const drafter = if (args.serial) null else if (given) args.drafter else known; @@ -399,7 +406,7 @@ fn run(ctx: *const Context, args: Args) !u8 { else => |x| return x, }; if (args.serial and given) note = try std.fmt.allocPrint(a, "--serial passes no drafter, so --drafter {s} is not used.", .{args.drafter}); - if (rocm and auto and !args.serial and model.knownDrafter(config.value) != null) note = "This run passes no drafter: " ++ hip_drafter ++ "."; + if (rocm and auto and !args.serial and model.knownDrafter(config.value) != null) note = "This run passes no drafter: on rocm only a named --drafter passes one."; if (known) |k| note = if (drafter_dir != null) try std.fmt.allocPrint(a, "This run passes the cached drafter {s}; --drafter none runs without it.", .{k}) else diff --git a/zig/src/server/benchmark_run_test.zig b/zig/src/server/benchmark_run_test.zig index 98501ab035e..6743847ab30 100644 --- a/zig/src/server/benchmark_run_test.zig +++ b/zig/src/server/benchmark_run_test.zig @@ -213,7 +213,7 @@ test "--drafter auto passes the family's drafter only when it is cached and says try std.testing.expect(!r.has(named) and try noDrafter(&r) and try passed(&r, "--no-drafts")); } -test "a rocm run refuses a named --drafter before any serve child, and auto names no drafter on rocm" { +test "a rocm run passes a named --drafter for qwen3_5 and refuses one for another family; auto names none on rocm" { var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); defer arena.deinit(); const a = arena.allocator(); @@ -221,6 +221,7 @@ test "a rocm run refuses a named --drafter before any serve child, and auto name var tmp = std.testing.tmpDir(.{}); defer tmp.cleanup(); var r = try Run.init(a, &tmp); + r.families = &.{ .{ .model_type = "qwen3_5", .formats = &.{} }, .{ .model_type = "qwen3_5_moe", .formats = &.{} } }; const m = try cli.managedWorld(a, false); defer m.stop(); r.self_exe = try cli.standIn(&r, m.port); @@ -232,8 +233,19 @@ test "a rocm run refuses a named --drafter before any serve child, and auto name try std.Io.Dir.cwd().createDirPath(io, big); const config = "{\"model_type\": \"qwen3_5\", \"hidden_size\": 5120, \"num_hidden_layers\": 64}"; try std.Io.Dir.cwd().writeFile(io, .{ .sub_path = try std.fs.path.join(a, &.{ big, "config.json" }), .data = config }); + // a named drafter passes; this host build's serve then refuses --backend rocm itself (a HIP build serves it) + const flags = "the managed server refuses its flags: --backend rocm"; for ([_][]const u8{ drafter, try r.path("hub") }) |named| { try std.testing.expectEqual(@as(u8, 1), try r.command(try argv(&r, &.{ big, "--backend", "rocm", "--drafter", named }))); + try std.testing.expect(r.has(flags) and !r.has(benchmark.rocm_drafter) and m.count() == 0); + } + // the sparse family has no DFlash2 drafter on HIP: refused before the run starts + const moe = try r.path("moe-checkpoint"); + try std.Io.Dir.cwd().createDirPath(io, moe); + const moe_config = "{\"model_type\": \"qwen3_5_moe\", \"hidden_size\": 2048, \"num_hidden_layers\": 40}"; + try std.Io.Dir.cwd().writeFile(io, .{ .sub_path = try std.fs.path.join(a, &.{ moe, "config.json" }), .data = moe_config }); + for ([_][]const u8{ drafter, try r.path("hub") }) |named| { + try std.testing.expectEqual(@as(u8, 1), try r.command(try argv(&r, &.{ moe, "--backend", "rocm", "--drafter", named }))); try std.testing.expect(r.has(benchmark.rocm_drafter) and !r.has("This generates model replies") and m.count() == 0); try missing(try r.path("pid")); try missing(try r.path(".tensorfold")); diff --git a/zig/tests/hip/contract_exl3.zig b/zig/tests/hip/contract_exl3.zig new file mode 100644 index 00000000000..9a181bdcf3b --- /dev/null +++ b/zig/tests/hip/contract_exl3.zig @@ -0,0 +1,437 @@ +//! EXL3's decode-row kernels under the contract on HIP: rot_in and the linear at each width, against float64. +const std = @import("std"); +const hip = @import("hip"); +const core = @import("core"); +const rig_ = @import("contract_rig.zig"); + +const contract = core.contract; +const c = contract.spec; +const g = contract.gates; +const fmt = core.exl3_format; +const exl3 = hip.launches.exl3; + +/// What a registration launches; a control runs its kind's kernel with one planted fault and must go red at gate 3. +pub const Reg = struct { rot: bool = false, halves: u32 = 8, bf16_out: bool = false, control: bool = false }; + +/// rot_in, the linear at every width with fp32 out (the head's) and at 4 bits with bf16 out, then a control of each. +pub const registrations = blk: { + var list: [exl3.widths.len + 4]Reg = undefined; + list[0] = .{ .rot = true }; + for (exl3.widths, 1..) |h, i| list[i] = .{ .halves = h }; + list[exl3.widths.len + 1] = .{ .bf16_out = true }; + list[exl3.widths.len + 2] = .{ .rot = true, .control = true }; + list[exl3.widths.len + 3] = .{ .control = true }; + break :blk list; +}; + +/// Whole 128-wide blocks from one block up: K and N of the linear. +const blocks: c.Tile = .{ .size = 128, .step = 128, .min = 128 }; + +fn sh(rows: usize, n: usize, k: usize) c.Shape { + return .{ .rows = rows, .n = n, .k = k }; +} + +// deepseek_v41's indexer wk (16, 64, 1 rows), gate 4's (Engram's K, one block), Engram's wkv, the 8-wave edge, below it +const linear_shapes = [_]c.Shape{ + sh(16, 128, 512), sh(64, 128, 512), sh(1, 128, 512), sh(1, 128, 6144), + sh(4, 25600, 6144), sh(4, 8192, 1024), sh(16, 8192, 1024), sh(4, 8064, 1024), +}; +// the head, 5120 to 129,280 at one row, registered at 8 bits: N sets only the grid +const head_shapes = linear_shapes ++ [_]c.Shape{sh(1, 129280, 5120)}; +// rot_in: n is a row's width (each output sums 128 terms); the same calls' inputs +const rot_shapes = [_]c.Shape{ sh(64, 512, 128), sh(16, 6144, 128), sh(2, 5120, 128) }; + +/// A K sum in any order, a wave's chain and the waves', then the output rotation's seven butterflies. +fn depth(s: c.Shape) usize { + return s.k + 64; +} + +/// The product x * suh, then seven butterflies. +fn rotDepth(_: c.Shape) usize { + return 8; +} + +const rot_why = "128-term rotations of bf16 inputs: fp32 is not exact on them, so gate 4 proves fp16's miss alone"; +const bf16_why = "bf16 outputs hide a bf16 sum's miss on these inputs; the fp32-output registrations prove fp32 sums"; + +fn name(r: Reg) []const u8 { + if (r.control and r.rot) return "control: tf_exl3_rot_in reads the next block's suh"; + if (r.control) return "control: tf_exl3_linear reads its input rows one row late"; + if (r.rot) return "hip exl3 tf_exl3_rot_in (bf16 rows to fp16)"; + inline for (exl3.widths) |h| if (h == r.halves) { + const fmt_ = "hip exl3 tf_exl3_linear_k{d}_w4 / _w8 ({d}-bit, 1-64 rows, {s} out)"; + if (r.bf16_out) return std.fmt.comptimePrint(fmt_, .{ h, h / 2, "bf16" }); + return std.fmt.comptimePrint(fmt_, .{ h, h / 2, "fp32" }); + }; + unreachable; +} + +pub fn spec(r: Reg) c.Spec { + if (r.rot) return .{ + .name = name(r), + .accum = .f32, + .depth = rotDepth, + .ops = 2, + .out = .f16, + .tiles = .{ .{}, .{ .size = 512, .step = 128, .min = 128 }, .{} }, + .served = &rot_shapes, + .sums = .{ .f16 = 4, .bf16 = 0, .exact = false, .why = rot_why }, + }; + return .{ + .name = name(r), + .accum = .f32, + .depth = depth, + .ops = 3, + .out = if (r.bf16_out) .bf16 else .f32, + .tiles = .{ .{ .size = 16 }, blocks, blocks }, + .served = if (r.halves == 16 and !r.bf16_out and !r.control) &head_shapes else &linear_shapes, + .sums = if (r.bf16_out) .{ .bf16 = 0, .why = bf16_why } else .{}, + }; +} + +pub const Case = struct { + rig: rig_.Rig, + l: *const hip.Launcher, + reg: Reg, + shape: c.Shape = undefined, + /// rot_in: x (bf16) and suh; the linear: xh (fp16), svh and the trellis in the checkpoint's layout + x: []u16 = &.{}, + scale: []u16 = &.{}, + trellis: []i16 = &.{}, + dx: u64 = 0, + dscale: u64 = 0, + dt: u64 = 0, + out: u64 = 0, + + pub fn init(a: std.mem.Allocator, rt: *const hip.Runtime, s: hip.Stream, l: *const hip.Launcher, reg: Reg) Case { + return .{ .rig = .{ .a = a, .r = rt, .s = s }, .l = l, .reg = reg }; + } + + pub fn deinit(self: *Case) void { + self.free(); + self.rig.deinit(); + } + + fn free(self: *Case) void { + self.rig.a.free(self.x); + self.rig.a.free(self.scale); + self.rig.a.free(self.trellis); + self.x = &.{}; + self.scale = &.{}; + self.trellis = &.{}; + } + + pub fn kernel(self: *Case) g.Kernel { + return .{ .spec = spec(self.reg), .ctx = self, .vt = &vt, .control = if (self.reg.control) .shapes else null }; + } + + const vt = g.hooks(Case); + + fn random16(rng: std.Random, out: []u16) void { + for (out) |*v| v.* = @bitCast(@as(f16, @floatCast(rng.float(f32) * 2 - 1))); + } + + /// Random inputs; non-finite: row 1's NaN, row 2's +Inf and -Inf; stress: see each kind's branch. + pub fn prepare(self: *Case, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + const k = if (self.reg.rot) shape.n else shape.k; + if (!exl3.fits(shape.rows, k, if (self.reg.rot) 128 else shape.n)) return false; + self.free(); + self.rig.reset(); + self.shape = shape; + const a = self.rig.a; + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + // a control reads one block (suh) or one row (xh) past the call's own, so those inputs carry one more + const extra_rows: usize = @intFromBool(self.reg.control and !self.reg.rot); + self.x = try a.alloc(u16, (shape.rows + extra_rows) * k); + const scales = if (self.reg.rot) k else shape.n; + self.scale = try a.alloc(u16, scales + if (self.reg.control) @as(usize, 128) else 0); + random16(rng, self.scale); + if (self.reg.rot) { + for (self.x) |*v| v.* = c.toBf16(rng.float(f32) * 2 - 1); + // stress: inputs to 64, as CUDA's rot_group (fp32 is not exact on 128-term rotations of them) + if (fill == .stress) for (self.x) |*v| { + v.* = c.toBf16(c.fromBf16(v.*) * 64); + }; + } else { + const w = fmt.Width{ .halves = @intCast(self.reg.halves) }; + self.trellis = try a.alloc(i16, (k / 16) * (shape.n / 16) * w.tileWords()); + random16(rng, self.x); + rng.bytes(std.mem.sliceAsBytes(self.trellis)); + // stress: all-ones states (one weight, -0.651), svh 1, xh 4096: K equal terms past fp16's range + if (fill == .stress) { + @memset(self.trellis, @bitCast(@as(u16, 0xffff))); + @memset(self.scale, 0x3c00); + @memset(self.x, @bitCast(@as(f16, 4096))); + } + self.dt = try self.rig.input(std.mem.sliceAsBytes(self.trellis)); + } + const nan: u16 = if (self.reg.rot) 0x7fc0 else 0x7e00; + const inf: u16 = if (self.reg.rot) 0x7f80 else 0x7c00; + if (fill == .nonfinite and shape.rows > 2) { + self.x[k + 3] = nan; + self.x[2 * k + 5] = inf; + self.x[2 * k + 9] = inf | 0x8000; + } + self.dx = try self.rig.input(std.mem.sliceAsBytes(self.x)); + self.dscale = try self.rig.input(std.mem.sliceAsBytes(self.scale)); + self.out = try self.rig.output(self.count() * (if (self.reg.rot or self.reg.bf16_out) @as(usize, 2) else 4)); + return true; + } + + pub fn count(self: *Case) usize { + return self.shape.rows * self.shape.n; + } + + pub fn run(self: *Case) !void { + const s = self.rig.s.handle; + const rows = self.shape.rows; + const fault: u64 = if (self.reg.control) 1 else 0; + if (self.reg.rot) { + try exl3.rotIn(self.l, self.dx, 2, self.dscale + fault * 128 * 2, self.out, rows, self.shape.n, s); + } else { + const k = self.shape.k; + const w = fmt.Width{ .halves = @intCast(self.reg.halves) }; + const tw: u64 = w.tileWords() / 2; + const t: exl3.Trellis = .{ + .words = self.dt, + .halves = self.reg.halves, + .stride_k = (self.shape.n / 16) * tw, + .stride_nb = 8 * tw, + }; + const kind: c_int = if (self.reg.bf16_out) 2 else 0; + try exl3.linear(self.l, self.dx + fault * k * 2, t, self.dscale, self.out, kind, rows, k, self.shape.n, s); + } + try self.rig.s.synchronize(); + } + + /// Float64 outputs and their terms' magnitude; with `acc`, each output's sums in that accumulator and order. + fn outputs(self: *Case, want: []f64, mag: ?[]f64, acc: ?c.Accum, order: g.Order) !void { + const a = self.rig.a; + const rows = self.shape.rows; + const n = self.shape.n; + if (self.reg.rot) { + // xh[j] = sum over q of H[q][j] / sqrt(128) * x[q] suh[q], block by block + const h = try a.alloc(f64, 128 * 128); + defer a.free(h); + @memset(h, 0); + for (0..128) |q| h[q * 128 + q] = 1; + fmt.rotate(h, 128, 128, 1); + var t: [128]f64 = undefined; + for (0..rows) |r| for (0..n / 128) |b| for (0..128) |j| { + var abs: f64 = 0; + for (&t, 0..) |*e, q| { + const i = b * 128 + q; + e.* = h[q * 128 + j] * c.fromBf16(self.x[r * n + i]) * half(self.scale[i]); + abs += @abs(e.*); + } + want[r * n + b * 128 + j] = if (acc) |ac| contract.rows.sumIn(ac, order, &t) else sum(&t); + if (mag) |m| m[r * n + b * 128 + j] = abs; + }; + return; + } + const k = self.shape.k; + const wq = try a.alloc(f16, k * n); + defer a.free(wq); + Unpack.all(self.reg.halves, self.trellis, k, n, wq); + const s1 = try a.alloc(f64, rows * n); + defer a.free(s1); + if (acc) |ac| { + const t = try a.alloc(f64, threads.maximum * k); + defer a.free(t); + const sims: Sims.Args = .{ .x = self.x, .wq = wq, .rows = rows, .k = k, .n = n, .acc = ac, .order = order }; + Sims.all(sims, t, want[0 .. rows * n]); + } else Sums.all(self.x, wq, rows, k, n, want[0 .. rows * n], s1); + rotate(want[0 .. rows * n], rows, n); + for (0..rows) |r| for (0..n) |j| { + const sc = half(self.scale[j]); + want[r * n + j] *= sc; + if (mag) |m| { + var s: f64 = 0; + for (j / 128 * 128..j / 128 * 128 + 128) |q| s += s1[r * n + q]; + m[r * n + j] = @abs(sc) * s / @sqrt(128.0); + } + }; + } + + /// Each row's 128-wide blocks through the unscaled butterflies, then the scale: exact where K sums are integers. + fn rotate(x: []f64, rows: usize, n: usize) void { + for (0..rows * n / 128) |b| { + const v = x[b * 128 ..][0..128]; + var d: usize = 1; + while (d < 128) : (d *= 2) { + var base: usize = 0; + while (base < 128) : (base += 2 * d) for (0..d) |j| { + const lo = v[base + j]; + const hi = v[base + j + d]; + v[base + j] = lo + hi; + v[base + j + d] = lo - hi; + }; + } + for (v) |*e| e.* /= @sqrt(128.0); + } + } + + fn sum(t: []const f64) f64 { + var s: f64 = 0; + for (t) |v| s += v; + return s; + } + + pub fn reference(self: *Case, want: []f64, mag: []f64) !void { + return self.outputs(want, mag, null, .sequential); + } + + pub fn simulate(self: *Case, acc: c.Accum, order: g.Order, out: []f64) !void { + return self.outputs(out, null, acc, order); + } +}; + +const threads = contract.reference_threads; + +/// W decoded as exl3_format's unpack does, by slices of K tiles on threads. +const Unpack = struct { + halves: u32, + trellis: []const i16, + n: usize, + tk0: usize, + tk1: usize, + wq: []f16, + + pub fn run(j: *Unpack) void { + const w = fmt.Width{ .halves = @intCast(j.halves) }; + const row = w.tileWords() * (j.n / 16); + const words = j.trellis[j.tk0 * row .. j.tk1 * row]; + fmt.unpack(w, .mul1, words, j.tk1 - j.tk0, j.n / 16, j.wq[j.tk0 * 16 * j.n .. j.tk1 * 16 * j.n]); + } + + fn all(halves: u32, trellis: []const i16, k: usize, n: usize, wq: []f16) void { + const count = threads.count(threads.maximum, k / 16); + var jobs: [threads.maximum]Unpack = undefined; + for (jobs[0..count], 0..) |*j, i| j.* = .{ + .halves = halves, + .trellis = trellis, + .n = n, + .tk0 = i * (k / 16) / count, + .tk1 = (i + 1) * (k / 16) / count, + .wq = wq, + }; + threads.run(Unpack, jobs[0..count], .normal); + } +}; + +/// Each output's K sum in float64, in K order, and its terms' magnitude: a range of columns on each thread. +const Sums = struct { + x: []const u16, + wq: []const f16, + rows: usize, + k: usize, + n: usize, + j0: usize, + j1: usize, + want: []f64, + s1: []f64, + + pub fn run(job: *Sums) void { + for (0..job.rows) |r| { + const y = job.want[r * job.n ..][job.j0..job.j1]; + const m = job.s1[r * job.n ..][job.j0..job.j1]; + @memset(y, 0); + @memset(m, 0); + for (0..job.k) |q| { + const xv = half(job.x[r * job.k + q]); + for (y, m, job.wq[q * job.n ..][job.j0..job.j1]) |*e, *s, wv| { + const p = xv * @as(f64, wv); + e.* += p; + s.* += @abs(p); + } + } + } + } + + fn all(x: []const u16, wq: []const f16, rows: usize, k: usize, n: usize, want: []f64, s1: []f64) void { + const count = threads.count(threads.maximum, n / 128); + var jobs: [threads.maximum]Sums = undefined; + for (jobs[0..count], 0..) |*j, i| j.* = .{ + .x = x, + .wq = wq, + .rows = rows, + .k = k, + .n = n, + .j0 = i * (n / 128) / count * 128, + .j1 = (i + 1) * (n / 128) / count * 128, + .want = want, + .s1 = s1, + }; + threads.run(Sums, jobs[0..count], .normal); + } +}; + +/// Gate 4's simulations: each output's K terms summed in an accumulator and order, a range of columns on each thread. +const Sims = struct { + x: []const u16, + wq: []const f16, + rows: usize, + k: usize, + n: usize, + j0: usize, + j1: usize, + acc: c.Accum, + order: g.Order, + t: []f64, + out: []f64, + + pub fn run(job: *Sims) void { + for (0..job.rows) |r| for (job.j0..job.j1) |j| { + for (job.t, 0..) |*e, q| e.* = half(job.x[r * job.k + q]) * @as(f64, job.wq[q * job.n + j]); + job.out[r * job.n + j] = contract.rows.sumIn(job.acc, job.order, job.t); + }; + } + + const Args = struct { + x: []const u16, + wq: []const f16, + rows: usize, + k: usize, + n: usize, + acc: c.Accum, + order: g.Order, + }; + + fn all(a: Args, t: []f64, out: []f64) void { + const count = threads.count(threads.maximum, a.n / 128); + var jobs: [threads.maximum]Sims = undefined; + for (jobs[0..count], 0..) |*j, i| j.* = .{ + .x = a.x, + .wq = a.wq, + .rows = a.rows, + .k = a.k, + .n = a.n, + .j0 = i * (a.n / 128) / count * 128, + .j1 = (i + 1) * (a.n / 128) / count * 128, + .acc = a.acc, + .order = a.order, + .t = t[i * a.k ..][0..a.k], + .out = out, + }; + threads.run(Sims, jobs[0..count], .normal); + } +}; + +fn half(b: u16) f64 { + return @as(f16, @bitCast(b)); +} + +// every served wave count is registered, and the stress sums (K terms of 4096 x -0.6513671875) are integers under 2^24 +comptime { + var four = false; + var eight = false; + var most: usize = 0; + for (linear_shapes) |s| { + if (exl3.waves(s.k, s.n) == 8) eight = true else four = true; + most = @max(most, s.k); + } + if (!four or !eight) @compileError("the linear registrations miss a wave count"); + if (most * 2668 >= 1 << 24 or fmt.codebookValue(.mul1, 0xffff) != -0.6513671875) + @compileError("the linear's stress sums are not exact in fp32"); +} diff --git a/zig/tests/hip/contract_main.zig b/zig/tests/hip/contract_main.zig index 0e476a52483..5455bd716c5 100644 --- a/zig/tests/hip/contract_main.zig +++ b/zig/tests/hip/contract_main.zig @@ -21,6 +21,7 @@ const relu2_k = @import("contract_relu2.zig"); const kv_k = @import("contract_kv_write.zig"); const tap_k = @import("contract_tap.zig"); const draft_k = @import("contract_draft.zig"); +const exl3_k = @import("contract_exl3.zig"); const argmax_k = @import("contract_argmax.zig"); const pair_k = @import("contract_relu2_pair.zig"); const heads_rows_k = @import("contract_heads_rows.zig"); @@ -259,6 +260,10 @@ fn run(a: std.mem.Allocator, io: std.Io) !usize { for (&drafts, draft_modes) |*m, w| m.* = .init(a, &r, s, &l, w); defer for (&drafts) |*m| m.deinit(); for (&drafts) |*m| try kernels.append(a, m.kernel()); + var exl3s: [exl3_k.registrations.len]exl3_k.Case = undefined; + for (&exl3s, exl3_k.registrations) |*m, reg| m.* = .init(a, &r, s, &l, reg); + defer for (&exl3s) |*m| m.deinit(); + for (&exl3s) |*m| try kernels.append(a, m.kernel()); var argmax = argmax_k.Argmax.init(a, &r, s, &l); defer argmax.deinit(); try kernels.append(a, argmax.kernel()); diff --git a/zig/tests/qwen35/check.zig b/zig/tests/qwen35/check.zig index d68f45a2206..e026f3ae101 100644 --- a/zig/tests/qwen35/check.zig +++ b/zig/tests/qwen35/check.zig @@ -1,4 +1,4 @@ -//! `check [--tp N --rank R] [--truth T --ids IDS] [--only invariants|accuracy|speed]`: a line a check. +//! `check [--tp N --rank R] [--truth T --ids IDS] [--only ...] [--drafter DIR]`: a line a check. const std = @import("std"); const qwen35 = @import("qwen3_5"); @@ -20,6 +20,8 @@ const Options = struct { prompts: ?[]const u8 = null, truth: ?[]const u8 = null, ids: ?[]const u8 = null, + /// A DFlash2 drafter's directory: the lane checks then draft with it in front of the target. + drafter: ?[]const u8 = null, speed: bool = false, explain: bool = false, only: ?Phase = null, @@ -53,9 +55,10 @@ fn parse(args: []const [:0]const u8) !Options { } 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 (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, "--drafter")) o.drafter = 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; + if (o.drafter != null and o.group.world > 1) return error.DrafterOnOneRank; return o; } @@ -107,13 +110,13 @@ pub fn run(gpa: std.mem.Allocator, io: std.Io, args: []const [:0]const u8) !u8 { return 0; } var session: lanes_session.Session = undefined; - try session.init(gpa, io, e, joined.link()); + try session.initDrafted(gpa, io, e, joined.link(), o.drafter, check_radix.most_streams); 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 }); + std.debug.print("check {s}, tp {d}{s}{s}\n", .{ o.model, o.group.world, if (o.drafter != null) ", drafter " else "", o.drafter orelse "" }); 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); diff --git a/zig/tests/qwen35/check_invariants.zig b/zig/tests/qwen35/check_invariants.zig index 06f7093ac12..571915d176c 100644 --- a/zig/tests/qwen35/check_invariants.zig +++ b/zig/tests/qwen35/check_invariants.zig @@ -106,7 +106,7 @@ fn lanesSet(c: *Ctx, set: []const u8, prompts: []const ids_file.Prompt) void { var serial = job; serial.drafts = false; const drafted = named(c, "lanes {s} {s}: drafted == serial", .{ set, d.name }); - if (c.session.h.head == null) { + if (c.session.h.head == null and c.session.drafted == 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; @@ -146,11 +146,51 @@ fn resumed(c: *Ctx) void { every = every and r.cached > 0; } var buf: [160]u8 = undefined; + if (differ(again, fresh, &buf)) |why| { + c.report.fail(name, "{s}", .{why}); + } else if (!every) { + c.report.fail(name, "a prompt resumed from no kept caches ({d} tokens kept in all)", .{cached}); + } else c.report.pass(name, "{d} streams, {d} tokens, {d} prompt tokens from the kept caches", .{ again.replies.len, again.tokens(), cached }); + resumedDrafted(c, extended, again); +} + +/// The resumed drafted run against the same prompts drafted from nothing kept: equal tokens, and each run's drafts. +fn resumedDrafted(c: *Ctx, extended: []const ids_file.Prompt, again: Session.Done) void { + const name = "lanes long greedy: resumed drafted == fresh drafted"; + if (c.session.h.head == null and c.session.drafted == null) return c.report.skip(name, "the model has no draft head"); + c.session.h.keepPrompts(0, 0); // evicts every kept prompt, so this run resumes from nothing + const fresh = c.session.run(c.arena, .{ .prompts = extended, .max_new = c.tokens, .solo = true }) catch |err| return c.report.broke(name, err); + for (fresh.replies) |r| if (r.cached != 0) return c.report.fail(name, "{s} resumed {d} tokens with no prompt kept", .{ r.name, r.cached }); + 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 }); + const a = Drafts.of(again); + const f = Drafts.of(fresh); + c.report.pass(name, "resumed {d}/{d} drafts kept in {d} rounds ({d:.2} tokens a round), fresh {d}/{d} in {d} ({d:.2})", .{ a.accepted, a.drafted, a.rounds, a.perRound(), f.accepted, f.drafted, f.rounds, f.perRound() }); } +/// A run's drafts summed over its streams. +const Drafts = struct { + rounds: u64 = 0, + accepted: u64 = 0, + drafted: u64 = 0, + tokens: usize = 0, + + fn of(d: Session.Done) Drafts { + var s: Drafts = .{}; + for (d.replies) |r| { + s.rounds += r.rounds; + s.accepted += r.accepted; + s.drafted += r.drafted; + s.tokens += r.tokens.len; + } + return s; + } + + fn perRound(s: Drafts) f64 { + return @as(f64, @floatFromInt(s.tokens)) / @as(f64, @floatFromInt(@max(s.rounds, 1))); + } +}; + /// 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"; diff --git a/zig/tests/qwen35/drafter_run.zig b/zig/tests/qwen35/drafter_run.zig index 0a4f8541329..9df9dd8bfee 100644 --- a/zig/tests/qwen35/drafter_run.zig +++ b/zig/tests/qwen35/drafter_run.zig @@ -6,6 +6,7 @@ const lanes = @import("lanes"); const qwen35 = @import("qwen3_5"); const Engine = qwen35.engine.Engine; +const Hip = qwen35.hip_lanes.Hip; const Draft = qwen35.draft.Draft; const Features = lanes.backend.Features; const Hold = lanes.drafter.Hold; @@ -180,6 +181,92 @@ fn refusals(d: *Draft, s: *lanes.Stream, f0: Features) !void { if (x.held(&.{s}, &.{out[0..4]}) != error.TooFewDrafts) return error.HeldNotRefused; try x.held(&.{s}, &.{out[0..3]}); for (out[0..3]) |t| if (t >= d.c.vocab) return error.DraftOutOfVocabulary; + // features of other rows than the absorb names, and a kept row past them + f.offset = 0; + const elsewhere = x.absorb(&.{.{ .stream = s, .features = f, .start = 4, .follow = &.{}, .prompt = false }}); + if (elsewhere != error.FeaturesNotAtStart) return error.StartNotHonoured; + f.offset = 4; + const past = x.absorb(&.{.{ .stream = s, .features = f, .start = 4, .follow = &.{}, .rows = &.{ 0, 4 } }}); + if (past != error.BadDraftRows) return error.KeptRowNotRefused; +} + +/// Rows a verified window of `wide` rows keeps (a tree's path, out of the first rows), and their count. +const picks = [_]u32{ 0, 5, 10, 15 }; +const wide = 16; + +/// One stream's chain after the prompt and an absorb at `p` (`ring`: the tap ring the features name). +fn keptChain(d: *Draft, s: *lanes.Stream, f0: Features, ring: u64, p: usize, rows: ?[]const u32, pending: u32) ![7]u32 { + const x = d.drafter(); + try x.open(s); + defer x.release(s); + var f = f0; + f.buffer = ring; + f.offset = 0; + f.rows = @intCast(p); + try x.absorb(&.{.{ .stream = s, .features = f, .start = 0, .follow = &.{} }}); + // kept rows pick from the window's rows; whole rows are as many of its first + f.offset = p; + f.rows = if (rows != null) wide else picks.len; + try x.absorb(&.{.{ .stream = s, .features = f, .start = p, .follow = &.{}, .rows = rows, .prompt = false }}); + var held: [7]u32 = undefined; + try x.hold(&.{.{ .stream = s, .pending = pending, .position = p + picks.len + 1, .depth = 7 }}); + try x.held(&.{s}, &.{&held}); + return held; +} + +/// Kept rows `picks` of a window draft as the first rows of a ring holding those rows in order, not as its first rows. +fn keptRows(e: *Engine, d: *Draft, s: *lanes.Stream, f: Features, p: usize, pending: u32) !void { + const t = e.model().taps; + const row: usize = f.row_bytes; + var alt = try hip.DeviceBuffer.alloc(&e.driver, t.rows * row); + defer alt.free(); + try e.stream.synchronize(); + try alt.copyFrom(0, f.buffer, t.rows * row); + for (picks, 0..) |from, to| try alt.copyFrom(((p + to) % t.rows) * row, f.buffer + ((p + from) % t.rows) * row, row); + const kept = try keptChain(d, s, f, f.buffer, p, &picks, pending); + const moved = try keptChain(d, s, f, alt.base(), p, null, pending); + if (!std.mem.eql(u32, &kept, &moved)) return error.KeptRowsDiffer; + const first = [_]u32{ 0, 1, 2, 3 }; + const prefix = try keptChain(d, s, f, f.buffer, p, &first, pending); + const whole = try keptChain(d, s, f, f.buffer, p, null, pending); + if (!std.mem.eql(u32, &prefix, &whole)) return error.KeptPrefixDiffers; + // rows the absorb ignored would draft as the first rows: the picks must move the chain to tell + if (std.mem.eql(u32, &kept, &whole)) return error.KeptRowsVacuous; +} + +/// A prompt past the tap ring through the lanes backend and Drafted, as the server runs it; then `features`' bounds. +fn served(gpa: std.mem.Allocator, e: *Engine, d: *Draft, prompt: []const u32) !void { + const h = try Hip.init(gpa, e); + defer h.deinit(); + const b = h.backend(); + var x = try lanes.drafted.Drafted.init(gpa, b, d.drafter()); + defer x.deinit(); + var s = try lanes.Stream.init(gpa, .{ .id = "long", .prompt = prompt, .max_new = 4 }); + defer s.deinit(gpa); + // the whole prompt's rows: the drafter reads its window's newest, still in the ring + try x.backend().prefill(&s); + defer x.backend().release(&s); + const taps = d.c.tapLayers(); + const len: u64 = prompt.len; + const ring: u64 = e.model().taps.rows; + const window: u64 = qwen35.engine.tap_window; + const whole = try b.features(&s, taps, 0, @intCast(len - 1)); + if (whole.offset != 0 or whole.rows != len - 1) return error.FeaturesMoved; + _ = try b.features(&s, taps, len - window, @intCast(window)); + const refused = [_][2]u64{ + .{ len - ring - 8, 16 }, // its first rows are out of the ring + .{ 0, 16 }, // all of them are + .{ len - 4, 5 }, // its last row is not written + .{ len - 4, 0 }, // no row + }; + for (refused) |r| { + const got = b.features(&s, taps, r[0], @intCast(r[1])); + if (got != error.RowsNotHeld) { + std.debug.print("FAIL drafter features [{d}, +{d}) of {d} rows in a {d}-row ring: served\n", .{ r[0], r[1], len, ring }); + return error.FeaturesNotBounded; + } + } + if (b.features(&s, taps[1..], 0, 4) != error.TapsMismatch) return error.TapsNotChecked; } /// The seeded sampled run: the target draws each continuation by `rule`, and the drafter's chains draw by it too. @@ -214,6 +301,10 @@ pub fn run(gpa: std.mem.Allocator, io: std.Io, args: []const [:0]const u8) !void return error.Usage; } const steps = if (args.len == 4) try std.fmt.parseInt(usize, args[3], 10) else 160; + if (steps < min_steps) { + std.debug.print("--steps {d}: at least {d}, so the rounds measure acceptance\n", .{ steps, min_steps }); + return error.Usage; + } var tok = try qwen35.tokenizer.loadTokenizer(io, gpa, args[1]); defer tok.deinit(); var prompts: [texts.len][]u32 = undefined; @@ -225,13 +316,17 @@ pub fn run(gpa: std.mem.Allocator, io: std.Io, args: []const [:0]const u8) !void longest = @max(longest, p.len); } defer for (prompts) |p| gpa.free(p); + // a prompt past the tap ring of 1024-row prompt chunks: the served path's eviction + const long = try gpa.alloc(u32, qwen35.engine.tap_window + qwen35.prefix.chunk + 256); + defer gpa.free(long); + for (long, 0..) |*t, i| t.* = prompts[i % prompts.len][(i / prompts.len) % prompts[i % prompts.len].len]; var target = try qwen35.Config.read(gpa, io, args[1]); defer target.deinit(); const c = try qwen35.draft_config.Config.read(gpa, io, args[0], qwen35.draft_config.Target.of(target.spec)); const policy = (try @import("group.zig").resolve("", 0)).policy; const e = try Engine.open(gpa, io, args[1], .{ - .capacity = longest + steps + 64, - .prompt_rows = longest + 16, + .capacity = @max(longest + steps, long.len + Hip.max_window) + 64, + .prompt_rows = qwen35.prefix.chunk, .streams = 1, .batch_rows = 16, .policy = policy, @@ -268,7 +363,11 @@ pub fn run(gpa: std.mem.Allocator, io: std.Io, args: []const [:0]const u8) !void plain_ms += try decode(io, e, &caches[n], prompt, greedy[n], null); } try refusals(d, &streams[0], features(e, c, &caches[0])); - std.debug.print("PASS drafter refusals: a hold behind its context, more drafts read than held\n", .{}); + std.debug.print("PASS drafter refusals: a hold behind its context, more drafts read than held, " ++ + "features of other rows, a kept row past them\n", .{}); + try keptRows(e, d, &streams[0], features(e, c, &caches[0]), prompts[0].len, greedy[0][4]); + std.debug.print("PASS drafter kept rows: rows {any} of {d} draft as those rows in order, not as the " ++ + "first rows; a prefix as whole rows\n", .{ picks, wide }); var alone: [texts.len]Rounds = undefined; var ran: usize = 0; defer for (alone[0..ran]) |*r| r.chains.deinit(gpa); @@ -288,6 +387,10 @@ pub fn run(gpa: std.mem.Allocator, io: std.Io, args: []const [:0]const u8) !void std.debug.print(fmt, .{ n, prompt.len, steps, a.rounds, a.first, a.rounds, per, per + 1, hold_ms, absorb_ms }); all.add(a); } + if (all.rounds < min_rounds) { + std.debug.print("FAIL drafter: {d} rounds, too few to judge acceptance (at least {d})\n", .{ all.rounds, min_rounds }); + return error.TooFewRounds; + } const plain = plain_ms / @as(f64, @floatFromInt(prompts.len)); const summary = "drafter acceptance over {d} rounds: first draft right {d:.3}, " ++ "mean acceptance length {d:.2} (kept drafts + bonus); plain decode {d:.2} ms a token\n"; @@ -318,8 +421,15 @@ pub fn run(gpa: std.mem.Allocator, io: std.Io, args: []const [:0]const u8) !void std.debug.print(fmt, .{ n, together, r.rounds, r.kept() + 1, alone[n].rounds, alone[n].kept() + 1, equal }); } try sampled(gpa, io, e, d, &prompts, steps); + try served(gpa, e, d, long); + std.debug.print("PASS drafter served: a {d}-token prompt through the lanes backend and Drafted; features " ++ + "serve its drafter window and refuse rows out of the ring, unwritten or none\n", .{long.len}); } +/// Greedy steps a prompt at least, and rounds over all prompts at least, for the acceptance to mean anything. +const min_steps = 64; +const min_rounds = 24; + /// The mean acceptance length under which the check fails: below a clean run's, above a ring read a slot behind. const min_length = 4.5; diff --git a/zig/tests/qwen35/lanes_session.zig b/zig/tests/qwen35/lanes_session.zig index c1bde4d1fee..413c7420f22 100644 --- a/zig/tests/qwen35/lanes_session.zig +++ b/zig/tests/qwen35/lanes_session.zig @@ -7,6 +7,7 @@ const qwen35 = @import("qwen3_5"); const ids_file = @import("ids_file.zig"); const Hip = qwen35.hip_lanes.Hip; +const Draft = qwen35.draft.Draft; pub const Session = struct { gpa: std.mem.Allocator, @@ -15,20 +16,61 @@ pub const Session = struct { h: *Hip, cfg: lanes.Config, clock: lanes.backend.WallClock, + /// The DFlash2 drafter `--drafter` loaded and the target wrapped behind it (null: the target drafts alone). + draft: ?*Draft = null, + drafted: ?lanes.drafted.Drafted = null, + /// The engine's taps before the drafter set its own, set again when the session ends. + taps: qwen35.view.Taps = .{}, /// 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 { + return s.initDrafted(gpa, io, e, link, null, 1); + } + + /// As `init`, with the DFlash2 drafter in `drafter` (null: none) in front, frames of up to `streams`. + pub fn initDrafted( + s: *Session, + gpa: std.mem.Allocator, + io: std.Io, + e: *qwen35.engine.Engine, + link: ?hip.collective.Link, + drafter: ?[]const u8, + streams: usize, + ) !void { + // as the native server opens it: taps set before the lanes make the streams' caches and rings + const taps = e.model().taps; + errdefer if (drafter != null) e.setTaps(taps.layers[0..taps.n]) catch {}; + const d: ?*Draft = if (drafter) |dir| try openDraft(gpa, io, e, dir, streams) else null; + errdefer if (d) |x| x.deinit(); 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 } }; + var drafted: ?lanes.drafted.Drafted = null; + if (d) |x| { + for (h.costs.window[0..h.costs.windows]) |c| x.setCost(c.width, c.ms); + drafted = try lanes.drafted.Drafted.init(gpa, h.backend(), x.drafter()); + } + errdefer if (drafted) |*x| x.deinit(); + const facts = if (drafted) |*x| x.facts(h.facts()) else h.facts(); + s.* = .{ .gpa = gpa, .io = io, .e = e, .h = h, .cfg = try lanes.Config.init(gpa, facts, rows, rows - 1), .clock = .{ .io = io }, .draft = d, .drafted = drafted }; + s.taps = taps; } pub fn deinit(s: *Session) void { s.cfg.deinit(s.gpa); + if (s.drafted) |*x| x.deinit(); s.h.deinit(); + if (s.draft) |d| { + d.deinit(); + s.e.setTaps(s.taps.layers[0..s.taps.n]) catch {}; + } + } + + /// What the lane core drives: the drafter's wrapper when there is one, else the target. + fn backend(s: *Session) lanes.backend.Backend { + return if (s.drafted) |*x| x.backend() else s.h.backend(); } pub const Job = struct { @@ -40,7 +82,7 @@ pub const Session = struct { solo: bool = false, }; - pub const Reply = struct { name: []const u8, tokens: []const u32, rounds: u64, accepted: u64, cached: u32 }; + pub const Reply = struct { name: []const u8, tokens: []const u32, rounds: u64, accepted: u64, drafted: u64, cached: u32 }; pub const Done = struct { replies: []const Reply, @@ -97,7 +139,7 @@ pub const Session = struct { } 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 }; + 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, .drafted = st.drafted, .cached = st.cached }; return .{ .replies = out, .seconds = seconds, @@ -112,7 +154,7 @@ pub const Session = struct { } fn finish(s: *Session, streams: []const *lanes.Stream) !void { - var engine = lanes.Engine.init(s.gpa, &s.cfg, s.h.backend(), s.clock.clock()); + var engine = lanes.Engine.init(s.gpa, &s.cfg, s.backend(), s.clock.clock()); defer engine.deinit(); for (streams) |st| try engine.addStream(st); while (engine.live.items.len > 0) try engine.step(); @@ -128,6 +170,16 @@ pub const Session = struct { } }; +/// The DFlash2 drafter in `dir` on `e`, its taps set first and a context ready for each of `streams`. +fn openDraft(gpa: std.mem.Allocator, io: std.Io, e: *qwen35.engine.Engine, dir: []const u8, streams: usize) !*Draft { + const c = try qwen35.draft_config.Config.read(gpa, io, dir, qwen35.draft_config.Target.of(e.model().spec)); + try e.setTaps(c.tapLayers()); + const d = try Draft.init(gpa, io, e, dir, @min(@max(streams, 1), qwen35.draft.max_streams)); + errdefer d.deinit(); + try d.reserve(streams); + return d; +} + 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; diff --git a/zig/tests/qwen35/main.zig b/zig/tests/qwen35/main.zig index 68ac3b7f3f9..01d16395fbf 100644 --- a/zig/tests/qwen35/main.zig +++ b/zig/tests/qwen35/main.zig @@ -10,7 +10,7 @@ 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] | hidden [--cut N|whole] [--layers] | readout [--len N] [--cut N, 0: the serving rule] [--streams K] | draw x | draft | drafter [--steps N]\n"; +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] [--drafter DIR] | upload [first layers] | digest [--tp N --rank R] | layers [--tp N --rank R [--master HOST] [--port P]] | lanes ... | prefill ... | logits [--f32] [--decode] | rows [n] | hidden [--cut N|whole] [--layers] | readout [--len N] [--cut N, 0: the serving rule] [--streams K] | draw x | draft | drafter [--steps N]\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 }{ diff --git a/zig/tests/qwen35/taps_run.zig b/zig/tests/qwen35/taps_run.zig index 19d23aa79af..7de02699d07 100644 --- a/zig/tests/qwen35/taps_run.zig +++ b/zig/tests/qwen35/taps_run.zig @@ -61,8 +61,12 @@ pub fn runCase(gpa: std.mem.Allocator, e: *Engine, ids: []const u32, n: usize) ! defer e.o.graphs = was; var buf: [5]u32 = undefined; const taps = layersOf(e.model().spec.n_layers, &buf); + // a drafter's taps, when one runs on this engine, come back after the case + const m = e.model(); + const before = m.taps; + const kept = before.layers[0..before.n]; try e.setTaps(taps); - defer e.setTaps(&.{}) catch {}; + defer e.setTaps(kept) catch {}; var caches = try e.newCaches(ids.len + 8); defer caches.deinit(gpa); const prompt = ids[0 .. ids.len - n]; @@ -107,8 +111,10 @@ fn secondRing(gpa: std.mem.Allocator, e: *Engine, taps: []const u32, ids: []cons const was = e.o.graphs; e.o.graphs = graphs; defer e.o.graphs = was; + // a drafter's taps, when one runs on this engine, come back after the case + const before = e.model().taps; try e.setTaps(taps); - defer e.setTaps(&.{}) catch {}; + defer e.setTaps(before.layers[0..before.n]) catch {}; // both streams live at once, so the second's ring is never the first's memory again var first = try e.newCaches(ids.len + 8); defer first.deinit(gpa);