diff --git a/CHANGELOG.md b/CHANGELOG.md index 9bb538cefb9..ab9f4f66982 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,8 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel ## Unreleased +- HIP: dense Qwen 3.5-family ModelOpt NVFP4 and FP8 checkpoints, refused before, load with their codes and E4M3 scales kept as stored (a group scale widens exactly to BF16 at read) and run on their own product kernels, whose rows have the same bits alone or in any round; a ModelOpt checkpoint is refused by name on an fp16 GPU, on more than one rank or with routed experts, and an FP8 weight holding a NaN code is refused at read (#2490). Thanks to @ElderOrb. + - Inkling 2 on CUDA reports no structured-output support and refuses a named or `required` `tool_choice` with a 400 before any prompt work, instead of a late 500 (#6132). - Build: share one compiled test binary across filtered host test steps on the same unfiltered root module, removing 297 redundant compiles (#6184) diff --git a/build.zig b/build.zig index ab31cc85db7..a2728da05e7 100644 --- a/build.zig +++ b/build.zig @@ -276,6 +276,7 @@ pub fn build(b: *std.Build) void { const with_hip = b.option(bool, "hip", "Enable the opt-in HIP backend and its host/device targets") orelse false; const hip_options = hip_build.options(b); // declared on every target (#1165), used only with -Dhip=true hip_build.loaderTests(b, test_step); + hip_build.headerTests(b, test_step); @import("zig/build/nemotron_parse.zig").hostTests(b, test_step); if (with_hip) hip_build.steps(b, target, optimize, build_options, test_step, hip_options); const with_vulkan = b.option(bool, "vulkan", "Enable the opt-in Vulkan backend and its host/device targets") orelse false; diff --git a/docs/quantization.md b/docs/quantization.md index ef55bd2fba2..032e601ec06 100644 --- a/docs/quantization.md +++ b/docs/quantization.md @@ -132,6 +132,31 @@ cold 8,192-token prompt in 4.41 s against `full`'s 7.96 s (1.81x; 1.82x at 2,048 52.3 ms against 50.1 ms without drafts: decode reads the same weight bytes either way, and `checkpoint` adds the rows' quantization. +## NVIDIA's NVFP4 checkpoints on HIP + +The HIP engine reads the same ModelOpt NVFP4 tensors as stored, without widening a weight: `weight` is U8 e2m1 codes +(even inputs in the low nibble of a byte), `weight_scale` an E4M3 scale every 16 inputs, and `weight_scale_2` the +projection's one global scale. One product kernel computes a projection for every row count, decoding a nibble to its +e2m1 level in BF16 with a table lookup and folding a group's 16 inputs in f32 before its scale, as the format's +reference does; this path serves BF16 activations only, since the engine refuses an FP16 build for a ModelOpt +checkpoint. The product is W4A16: four bits of codes and one of scale a weight come to five bits, about 31% of a BF16 +weight's bytes, and a decode reads about a third of the traffic. + +The device keeps the checkpoint's own layout, as the MLX affine format does, so an upload is a copy. The only +transform is at read: an E4M3 group scale widens to BF16, exactly (three mantissa bits fit seven), which is the 16-bit +table the kernel reads. A stack of experts is refused, as BF16's is, because ModelOpt writes one global scale a +projection. + +An FP8 layer is stored the same way, its E4M3 codes one a byte and one f32 scale a projection. A sibling kernel decodes +each code to the exact f32 it names, sums all of K in f32 and multiplies the scale once, so the layer is exact and +row-invariant, and it does not go through rocBLAS. + +One kernel serves a prompt's rows and a round's, so a row's bits depend on its own inputs alone and not on how many +rows its round carries. A product of the kernel stays inside the bound a chain of k fmaf and one a group allows of the +format's f64 reference, and a row computed alone equals the same row in a round of seventeen, bit for bit, with K past +a chunk. The CUDA engine serves these checkpoints too; a backend that does not read the format refuses it by name +rather than reading the codes as something else. + ## GLM-5.3-Flash's float32 tensors on CUDA The GLM CUDA loader keeps float32 where its kernels read float32: the hyper-connections' bases and scales, KDA's short diff --git a/zig/build/checkpoint_io_host.zig b/zig/build/checkpoint_io_host.zig index 451ed18177f..4349e0bad42 100644 --- a/zig/build/checkpoint_io_host.zig +++ b/zig/build/checkpoint_io_host.zig @@ -19,5 +19,6 @@ pub fn steps(b: *std.Build, target: std.Build.ResolvedTarget) void { .dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = core, .filters = &.{"gptq:"} })).step); const qwen = b.createModule(.{ .root_source_file = b.path("zig/src/families/qwen3_5/loader.zig"), .target = target, .optimize = mode, .link_libc = true, .imports = &.{.{ .name = "core", .module = core }} }); step.dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = qwen, .filters = &.{"Qwen shard integrity:"} })).step); + if (mode == .debug) step.dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = qwen, .filters = &.{"MTP source:"} })).step); } } diff --git a/zig/build/hip.zig b/zig/build/hip.zig index 4ddba61b0d3..d32dd252d88 100644 --- a/zig/build/hip.zig +++ b/zig/build/hip.zig @@ -56,6 +56,16 @@ pub fn loaderTests(b: *std.Build, test_step: *std.Build.Step) void { loader.step.dependOn(@import("mesh.zig").qwenDeclTest(b, coreModule(b, b.graph.host))); // its cuts as declarations b.step("test-qwen35", "Qwen3.5 / 3.6 checkpoint loader tests; TF_QWEN_DIR indexes a real checkpoint").dependOn(&loader.step); } +/// The kernel dependency scan: part of `test` on every build, HIP or not, so a dropped include is caught. +pub fn headerTests(b: *std.Build, test_step: *std.Build.Step) void { + const run = b.addRunArtifact(b.addTest(.{ .root_module = b.createModule(.{ + .root_source_file = b.path("zig/build/hip_headers.zig"), + .target = b.graph.host, + .link_libc = true, + }) })); + test_step.dependOn(&run.step); + b.step("test-hip-headers", "The HIP dependency scan: every .hpp and each .hip a source includes").dependOn(&run.step); +} /// hip-host-test (part of `test`), hip-gpu-build and hip-gpu-test, hip-affine-build and hip-affine-test. pub fn steps(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builtin.OptimizeMode, build_options: *std.Build.Step.Options, test_step: *std.Build.Step, o: Options) void { const hip_fixtures = b.addOptions(); @@ -512,18 +522,8 @@ const groups = [_]Source{ .{ .path = "inkling2/dense.hip", .strict = true }, .{ .path = "inkling2/logits.hip", .strict = true }, }; -/// What the group sources include, so an edit to one rebuilds them. -const headers = [_][]const u8{ - "attention/attention_fa.hip", "attention/prefill.hpp", "decode/pages.hpp", "decode/plan.hpp", "ops/attention.hpp", "ops/common.hpp", - "ops/draw.hpp", "ops/tp.hpp", "ops/elementwise.hpp", "ops/linear.hpp", "ops/moe.hpp", "ops/norms.hpp", - "ops/rope.hpp", "common/arch.hpp", "common/dot2.hpp", "common/vec.hpp", "common/wmma.hpp", "quant/act.hpp", - "quant/mlx.hpp", "quant/mlx_decoder.hpp", "quant/mlx_pieces.hpp", "quant/mlx_tiles.hpp", "tiles/dot2.hpp", "tiles/epilogue.hpp", - "tiles/gemm.hpp", "tiles/gemm_kp.hpp", "tiles/matrix_gemm.hpp", "tiles/matrix_item.hpp", "tiles/plan.hpp", "tiles/stream.hpp", - "flashnext/streams.hpp", "flashnext/ngram.hpp", "flashnext/indexer.hpp", "flashnext/sparse.hpp", "ops/nemotron_moe.hpp", "quant/bf16_decoder.hpp", - "quant/dense_tiles.hpp", "tiles/wmma12_gemm.hpp", "tiles/wmma12_gemm_k32_ref.hpp", "ops/columns.hpp", "columns_controls.hpp", "ops/vision.hpp", - "ops/dense_text.hpp", "ops/vl_position.hpp", "flashnext/sparse_lanes.hpp", "tiles/wmma12_step.hpp", "inkling2/tile.hpp", "inkling2/zmath.hpp", - "inkling2/experts.hpp", "inkling2/q4.hpp", -}; +/// What the group sources include, so an edit to one rebuilds them: every .hpp under the kernels root. +const headers = @import("hip_headers.zig"); /// The flags of the kernels' first build: no contraction, wave32 on RDNA, C++20. const flags = [_][]const u8{ "-D__HIP_PLATFORM_AMD__=1", "-DUSE_ROCM=1", "-DHIPBLAS_V2", "-fPIC", "-DCUDA_HAS_FP16=1", "-DHIP_ENABLE_WARP_SYNC_BUILTINS=1", "-std=c++20", "-fno-gpu-rdc", "-mno-wavefrontsize64", "-ffp-contract=off" }; const stub = std.fmt.comptimePrint("pub const arch = \"\";\npub const images: [{d}][]align(8) const u8 = @splat(&.{{}});\n", .{groups.len}); @@ -577,7 +577,7 @@ fn compileSource(b: *std.Build, cc: Hipcc, arch: []const u8, source: LazyPath, o // clang 21 leaves a branch of affine_dot2_stream_relu2_pair past simm16 on gfx1100 (#1521) if (cc.relax_branches and std.mem.eql(u8, arch, "gfx1100")) run.addArgs(&.{ "-mllvm", "-amdgpu-s-branch-bits=15" }); run.addPrefixedDirectoryArg("-I", b.path("zig/kernels/hip")); - for (headers) |h| run.addFileInput(b.path(b.fmt("zig/kernels/hip/{s}", .{h}))); + for (headers.of(b)) |h| run.addFileInput(b.path(b.fmt("zig/kernels/hip/{s}", .{h}))); run.addArg("-o"); const object = run.addOutputFileArg(out); run.addFileArg(source); diff --git a/zig/build/hip_headers.zig b/zig/build/hip_headers.zig new file mode 100644 index 00000000000..fbb6b7d3868 --- /dev/null +++ b/zig/build/hip_headers.zig @@ -0,0 +1,85 @@ +//! Every file a HIP group source depends on, so an edit to one rebuilds the code objects that include it. +const std = @import("std"); + +/// The .hpp headers and the files a source includes under root, walked: a list is one a new header can be left out of. +pub fn collect(a: std.mem.Allocator, io: std.Io, root: []const u8) ![]const []const u8 { + var out: std.ArrayList([]const u8) = .empty; + errdefer { + for (out.items) |p| a.free(p); + out.deinit(a); + } + var seen: std.StringHashMapUnmanaged(void) = .empty; + defer seen.deinit(a); + var dir = try std.Io.Dir.cwd().openDir(io, root, .{ .iterate = true }); + defer dir.close(io); + var walk = try dir.walk(a); + defer walk.deinit(); + while (try walk.next(io)) |e| { + if (e.kind != .file) continue; + if (std.mem.endsWith(u8, e.path, ".hpp")) try keep(a, &out, &seen, try a.dupe(u8, e.path)); + // the file's own local includes are dependencies too: a .hip (attention_fa.hip) or a shared .hpp + const text = std.Io.Dir.cwd().readFileAlloc(io, try std.fs.path.join(a, &.{ root, e.path }), a, .limited(1 << 24)) catch continue; + defer a.free(text); + var lines = std.mem.splitScalar(u8, text, '\n'); + while (lines.next()) |line| if (includeTarget(line)) |target| { + if (try resolve(a, dir, io, e.path, target)) |path| try keep(a, &out, &seen, path); + }; + } + std.mem.sort([]const u8, out.items, {}, struct { + fn less(_: void, x: []const u8, y: []const u8) bool { + return std.mem.lessThan(u8, x, y); + } + }.less); + return out.items; +} + +/// The `"..."` of a `#include "..."` line, or null: an angle-bracket include is a system header, not ours. +fn includeTarget(line: []const u8) ?[]const u8 { + const trimmed = std.mem.trim(u8, line, " \t\r"); + if (!std.mem.startsWith(u8, trimmed, "#include")) return null; + const rest = std.mem.trimStart(u8, trimmed["#include".len..], " \t"); + if (rest.len < 2 or rest[0] != '"') return null; + const end = std.mem.indexOfScalarPos(u8, rest, 1, '"') orelse return null; + return rest[1..end]; +} + +/// `target` as a path under `root`: beside the including file first, as clang reads `"..."`, then at the `-I` root. +fn resolve(a: std.mem.Allocator, dir: std.Io.Dir, io: std.Io, from: []const u8, target: []const u8) !?[]const u8 { + if (std.fs.path.isAbsolute(target)) return null; + const beside = try std.fs.path.join(a, &.{ std.fs.path.dirname(from) orelse "", target }); + if (dir.statFile(io, beside, .{})) |_| return beside else |_| a.free(beside); + if (dir.statFile(io, target, .{})) |_| return try a.dupe(u8, target) else |_| {} + return null; +} + +/// Appends `path` once, freeing it when it is already held. +fn keep(a: std.mem.Allocator, out: *std.ArrayList([]const u8), seen: *std.StringHashMapUnmanaged(void), path: []const u8) !void { + if ((try seen.getOrPut(a, path)).found_existing) { + a.free(path); + return; + } + try out.append(a, path); +} + +/// `collect` over the engine's own kernels root, for the build's code object inputs. +pub fn of(b: *std.Build) []const []const u8 { + return collect(b.allocator, b.graph.io, "zig/kernels/hip") catch @panic("the kernels header walk failed"); +} + +test "the dependency scan takes every .hpp and the .hip a source includes, and no other" { + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + const io = std.testing.io; + try tmp.dir.writeFile(io, .{ .sub_path = "attention.hip", .data = "#include \n#include \"attention_fa.hip\"\n" }); + try tmp.dir.writeFile(io, .{ .sub_path = "attention_fa.hip", .data = "// included device code\n" }); + try tmp.dir.writeFile(io, .{ .sub_path = "gemm.hpp", .data = "// a header\n" }); + try tmp.dir.writeFile(io, .{ .sub_path = "dot2.hip", .data = "// a compiland that includes nothing\n" }); + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const root = try std.fmt.allocPrint(arena.allocator(), ".zig-cache/tmp/{s}", .{tmp.sub_path}); + const got = try collect(arena.allocator(), io, root); + // attention.hip's include is a dependency; the compiland itself and dot2.hip are not + try std.testing.expectEqual(@as(usize, 2), got.len); + try std.testing.expectEqualStrings("attention_fa.hip", got[0]); + try std.testing.expectEqualStrings("gemm.hpp", got[1]); +} diff --git a/zig/kernels/hip/quant/fp8_tiles.hpp b/zig/kernels/hip/quant/fp8_tiles.hpp new file mode 100644 index 00000000000..8bb523c00e4 --- /dev/null +++ b/zig/kernels/hip/quant/fp8_tiles.hpp @@ -0,0 +1,153 @@ +#pragma once + +// ModelOpt FP8's product: an E4M3 code a byte, one f32 scale a projection, the sum in f32 and the scale once. + +#include +#include + +#include + +namespace tf { +namespace rocm { + +constexpr int kFpTileM = 64; +constexpr int kFpTileN = 64; +constexpr int kFpChunk = 64; // codes a chunk +constexpr int kFpSmallM = 16; // rows a decode block serves + +struct ModelFp8 { + const void* x; // (m, k) row major, bf16 + const void* codes; // (n, k) row major, E4M3 one a byte + const float* scale; // (1): the projection's one scale + float* out; // (m, n) + int m, n, k; +}; + +// An E4M3 code as the f32 it names, exactly: 0x7f and 0xff are NaN and refused at read. +__device__ __forceinline__ float fp8_level(unsigned c) { + const unsigned e = (c >> 3) & 0xfu, m = c & 0x7u; + const float v = e == 0 ? static_cast(m) * 0.125f * __uint_as_float((127u - 6u) << 23) + : (1.0f + static_cast(m) * 0.125f) * __uint_as_float((e + 120u) << 23); + return (c & 0x80u) != 0 ? -v : v; +} + +// The row a block reads, clamped so a block past the end reads the last row. +__device__ __forceinline__ int fp8_row(int m, int row) { return row < m ? row : m - 1; } + +// A 64 x 64 block: a chunk of every column's codes and the block's rows of x staged in LDS once, each thread's 4 x 4 +// outputs accumulated over them; the projection's one scale multiplies each output once. +__device__ __forceinline__ void fp8_block(ModelFp8 a) { + __shared__ unsigned char codes[kFpTileN][kFpChunk]; + __shared__ hip_bfloat16 xs[kFpTileM][kFpChunk]; + const int tid = threadIdx.x; + const int ty = tid & (kFpTileM / 4 - 1); + const int tx = tid / (kFpTileM / 4); + const int n0 = blockIdx.x * kFpTileN; + const int m0 = blockIdx.y * kFpTileM; + const unsigned char* w = static_cast(a.codes); + const hip_bfloat16* x = static_cast(a.x); + float acc[4][4]; +#pragma unroll + for (int r = 0; r < 4; ++r) { +#pragma unroll + for (int c = 0; c < 4; ++c) acc[r][c] = 0.f; + } + for (int kc = 0; kc < a.k; kc += kFpChunk) { + for (int i = tid; i < kFpTileN * kFpChunk; i += blockDim.x) { + const int col = i / kFpChunk, j = i % kFpChunk; + const int c = n0 + col < a.n ? n0 + col : a.n - 1; + const int at = kc + j < a.k ? kc + j : a.k - 1; + codes[col][j] = w[static_cast(c) * a.k + at]; + } + for (int i = tid; i < kFpTileM * kFpChunk; i += blockDim.x) { + const int row = i / kFpChunk, j = i % kFpChunk; + const int r = fp8_row(a.m, m0 + row); + xs[row][j] = kc + j < a.k ? x[static_cast(r) * a.k + kc + j] : hip_bfloat16(0.f); + } + __syncthreads(); +#pragma unroll + for (int c = 0; c < 4; ++c) { + const int col = tx * 4 + c; + float q[4]; +#pragma unroll + for (int r = 0; r < 4; ++r) q[r] = 0.f; + // not unrolled: 64 steps of four rows spill the thread's registers + for (int j = 0; j < kFpChunk; ++j) { + const float lvl = fp8_level(codes[col][j]); +#pragma unroll + for (int r = 0; r < 4; ++r) { + q[r] = fmaf(lvl, static_cast(xs[ty * 4 + r][j]), q[r]); + } + } +#pragma unroll + for (int r = 0; r < 4; ++r) acc[r][c] += q[r]; + } + __syncthreads(); + } + const float scale = a.scale[0]; +#pragma unroll + for (int r = 0; r < 4; ++r) { + const int row = m0 + ty * 4 + r; + if (row >= a.m) continue; +#pragma unroll + for (int c = 0; c < 4; ++c) { + const int col = n0 + tx * 4 + c; + if (col >= a.n) continue; + a.out[static_cast(row) * a.n + col] = acc[r][c] * scale; + } + } +} + +// A 16-row block, as NVFP4's: one row four columns a thread, the same sums the 64-row tile makes. +__device__ __forceinline__ void fp8_small(ModelFp8 a) { + __shared__ unsigned char codes[kFpTileN][kFpChunk]; + __shared__ hip_bfloat16 xs[kFpSmallM][kFpChunk]; + const int tid = threadIdx.x; + const int row = tid >> 4; + const int c0 = (tid & 15) * 4; + const int n0 = blockIdx.x * kFpTileN; + const unsigned char* w = static_cast(a.codes); + const hip_bfloat16* x = static_cast(a.x); + float acc[4]; +#pragma unroll + for (int c = 0; c < 4; ++c) acc[c] = 0.f; + for (int kc = 0; kc < a.k; kc += kFpChunk) { + for (int i = tid; i < kFpTileN * kFpChunk; i += blockDim.x) { + const int col = i / kFpChunk, j = i % kFpChunk; + const int c = n0 + col < a.n ? n0 + col : a.n - 1; + const int at = kc + j < a.k ? kc + j : a.k - 1; + codes[col][j] = w[static_cast(c) * a.k + at]; + } + for (int i = tid; i < kFpSmallM * kFpChunk; i += blockDim.x) { + const int rr = i / kFpChunk, j = i % kFpChunk; + const int rw = fp8_row(a.m, rr); + xs[rr][j] = kc + j < a.k ? x[static_cast(rw) * a.k + kc + j] : hip_bfloat16(0.f); + } + __syncthreads(); +#pragma unroll + for (int c = 0; c < 4; ++c) { + const int col = c0 + c; + float q = 0.f; + for (int j = 0; j < kFpChunk; ++j) { + q = fmaf(fp8_level(codes[col][j]), static_cast(xs[row][j]), q); + } + acc[c] += q; + } + __syncthreads(); + } + const float scale = a.scale[0]; +#pragma unroll + for (int c = 0; c < 4; ++c) { + const int col = n0 + c0 + c; + if (row < a.m and col < a.n) a.out[static_cast(row) * a.n + col] = acc[c] * scale; + } +} + +} // namespace rocm +} // namespace tf + +// This path serves bf16 activations only, as the NVFP4 product does. +extern "C" __global__ void __launch_bounds__(256) tf_fp8_gemm(tf::rocm::ModelFp8 a) { + if (a.m >= tf::rocm::kFpSmallM) tf::rocm::fp8_block(a); + else tf::rocm::fp8_small(a); +} diff --git a/zig/kernels/hip/quant/nvfp4.hpp b/zig/kernels/hip/quant/nvfp4.hpp new file mode 100644 index 00000000000..f96c83d58b0 --- /dev/null +++ b/zig/kernels/hip/quant/nvfp4.hpp @@ -0,0 +1,34 @@ +#pragma once + +// ModelOpt NVFP4's words: e2m1 codes eight to a word, one E4M3 group scale a 16 inputs, one global scale. + +#include +#include +#include + +#include + +#include "quant/mlx.hpp" +#include "tiles/plan.hpp" + +namespace tf { +namespace rocm { + + +// e2m1's sixteen levels as BF16 bits, so a nibble's level is one load and no conversion. +__device__ constexpr unsigned short kE2m1Bf16[16] = { + 0x0000, 0x3F00, 0x3F80, 0x3FC0, 0x4000, 0x4040, 0x4080, 0x40C0, + 0x8000, 0xBF00, 0xBF80, 0xBFC0, 0xC000, 0xC040, 0xC080, 0xC0C0, +}; +struct Nvfp4 { + const void* x; // (m, k) row major, bf16 + const uint32_t* words; // (n, k / 8) row major: 4-bit codes, 8 to a word + GroupTable scale; // (n, k / 16), E4M3's values as BF16 + float* out; // (m, n) + int m, n, k, group; + float global = 1.0f; // the checkpoint's second scale, applied to the widened group scale +}; + + +} // namespace rocm +} // namespace tf diff --git a/zig/kernels/hip/quant/nvfp4_tiles.hpp b/zig/kernels/hip/quant/nvfp4_tiles.hpp new file mode 100644 index 00000000000..aa29b505c6a --- /dev/null +++ b/zig/kernels/hip/quant/nvfp4_tiles.hpp @@ -0,0 +1,262 @@ +#pragma once + +// ModelOpt NVFP4: e2m1 codes eight to a word, one E4M3 group scale a 16 inputs, and the projection's global scale. + +#include +#include +#include + +#include + +#include "quant/nvfp4.hpp" + +namespace tf { +namespace rocm { + +constexpr int kNvTileM = 64; +constexpr int kNvTileN = 64; +constexpr int kNvChunk = 64; // codes a chunk: four groups, eight words a column +constexpr int kNvSmallM = 16; // rows a decode block serves +constexpr int kNvWords = kNvChunk / 8; +constexpr int kNvDepth = 2; // chunks of codes a column keeps in flight + +// The group table's entry at `i` as the float it holds: BF16's bits shifted into f32. +__device__ __forceinline__ float nvfp4_scale(const GroupTable& t, long long i) { + return __uint_as_float(static_cast(static_cast(t.p)[i]) << 16); +} + +// A nibble's e2m1 level as a float: the BF16 bit table shifted into f32, which is the same value. +__device__ __forceinline__ float nvfp4_level(uint32_t code) { + return __uint_as_float(static_cast(kE2m1Bf16[code & 0xfu]) << 16); +} + +// The row a block reads, clamped so a block past the end reads the last row. +__device__ __forceinline__ int nvfp4_row(int m, int row) { return row < m ? row : m - 1; } + +// A 64 x 64 block: a chunk of every column's codes and its group scales, and the block's rows of x, staged in LDS once +// and each thread's 4 x 4 outputs accumulated over them. A group folds its 16 inputs before its scale. +__device__ __forceinline__ void nvfp4_block(Nvfp4 a) { + __shared__ uint32_t codes[kNvTileN][kNvChunk / 8]; + __shared__ float sc[kNvTileN][kNvChunk / 16]; + __shared__ hip_bfloat16 xs[kNvTileM][kNvChunk]; + const int tid = threadIdx.x; + const int ty = tid & (kNvTileM / 4 - 1); + const int tx = tid / (kNvTileM / 4); + const int n0 = blockIdx.x * kNvTileN; + const int m0 = blockIdx.y * kNvTileM; + const int words_row = a.k / 8; + const int groups = a.k / a.group; + const hip_bfloat16* x = static_cast(a.x); + float acc[4][4]; +#pragma unroll + for (int r = 0; r < 4; ++r) { +#pragma unroll + for (int c = 0; c < 4; ++c) acc[r][c] = 0.f; + } + for (int kc = 0; kc < a.k; kc += kNvChunk) { + for (int i = tid; i < kNvTileN * (kNvChunk / 8); i += blockDim.x) { + const int col = i / (kNvChunk / 8), wd = i % (kNvChunk / 8); + const int c = n0 + col < a.n ? n0 + col : a.n - 1; + const int at = kc / 8 + wd < words_row ? kc / 8 + wd : words_row - 1; + codes[col][wd] = a.words[static_cast(c) * words_row + at]; + } + for (int i = tid; i < kNvTileN * (kNvChunk / 16); i += blockDim.x) { + const int col = i / (kNvChunk / 16), g = i % (kNvChunk / 16); + const int c = n0 + col < a.n ? n0 + col : a.n - 1; + const int gi = kc / 16 + g < groups ? kc / 16 + g : groups - 1; + sc[col][g] = nvfp4_scale(a.scale, static_cast(c) * groups + gi); + } + for (int i = tid; i < kNvTileM * kNvChunk; i += blockDim.x) { + const int row = i / kNvChunk, j = i % kNvChunk; + const int r = nvfp4_row(a.m, m0 + row); + xs[row][j] = kc + j < a.k ? x[static_cast(r) * a.k + kc + j] : hip_bfloat16(0.f); + } + __syncthreads(); +#pragma unroll + for (int g = 0; g < kNvChunk / 16; ++g) { +#pragma unroll + for (int c = 0; c < 4; ++c) { + const int col = tx * 4 + c; + const float scale = sc[col][g]; + float q[4]; +#pragma unroll + for (int r = 0; r < 4; ++r) q[r] = 0.f; +#pragma unroll + for (int j = 0; j < 16; ++j) { + const int code = g * 16 + j; + const float lvl = nvfp4_level(codes[col][code / 8] >> (4 * (code % 8))); +#pragma unroll + for (int r = 0; r < 4; ++r) { + q[r] = fmaf(lvl, static_cast(xs[ty * 4 + r][code]), q[r]); + } + } +#pragma unroll + for (int r = 0; r < 4; ++r) acc[r][c] = fmaf(q[r], scale, acc[r][c]); + } + } + __syncthreads(); + } +#pragma unroll + for (int r = 0; r < 4; ++r) { + const int row = m0 + ty * 4 + r; + if (row >= a.m) continue; +#pragma unroll + for (int c = 0; c < 4; ++c) { + const int col = n0 + tx * 4 + c; + if (col >= a.n) continue; + a.out[static_cast(row) * a.n + col] = acc[r][c] * a.global; + } + } +} + +// A 16-row block: one row four columns a thread, so a decode round computes its own rows. A group's 16 inputs fold in +// the same order as the 64-row tile's, so a row's bits are the tile's whatever its round's size. +__device__ __forceinline__ void nvfp4_small(Nvfp4 a) { + __shared__ uint32_t codes[kNvTileN][kNvWords]; + __shared__ float sc[kNvTileN][kNvChunk / 16]; + __shared__ hip_bfloat16 xs[kNvSmallM][kNvChunk]; + const int tid = threadIdx.x; + const int row = tid >> 4; + const int c0 = (tid & 15) * 4; + const int n0 = blockIdx.x * kNvTileN; + const int words_row = a.k / 8; + const int groups = a.k / a.group; + const hip_bfloat16* x = static_cast(a.x); + float acc[4]; +#pragma unroll + for (int c = 0; c < 4; ++c) acc[c] = 0.f; + for (int kc = 0; kc < a.k; kc += kNvChunk) { + for (int i = tid; i < kNvTileN * (kNvChunk / 8); i += blockDim.x) { + const int col = i / (kNvChunk / 8), wd = i % (kNvChunk / 8); + const int c = n0 + col < a.n ? n0 + col : a.n - 1; + const int at = kc / 8 + wd < words_row ? kc / 8 + wd : words_row - 1; + codes[col][wd] = a.words[static_cast(c) * words_row + at]; + } + for (int i = tid; i < kNvTileN * (kNvChunk / 16); i += blockDim.x) { + const int col = i / (kNvChunk / 16), g = i % (kNvChunk / 16); + const int c = n0 + col < a.n ? n0 + col : a.n - 1; + const int gi = kc / 16 + g < groups ? kc / 16 + g : groups - 1; + sc[col][g] = nvfp4_scale(a.scale, static_cast(c) * groups + gi); + } + for (int i = tid; i < kNvSmallM * kNvChunk; i += blockDim.x) { + const int rr = i / kNvChunk, j = i % kNvChunk; + const int rw = nvfp4_row(a.m, rr); + xs[rr][j] = kc + j < a.k ? x[static_cast(rw) * a.k + kc + j] : hip_bfloat16(0.f); + } + __syncthreads(); +#pragma unroll + for (int g = 0; g < kNvChunk / 16; ++g) { +#pragma unroll + for (int c = 0; c < 4; ++c) { + const int col = c0 + c; + float q = 0.f; +#pragma unroll + for (int j = 0; j < 16; ++j) { + const int code = g * 16 + j; + q = fmaf(nvfp4_level(codes[col][code / 8] >> (4 * (code % 8))), static_cast(xs[row][code]), q); + } + acc[c] = fmaf(q, sc[col][g], acc[c]); + } + } + __syncthreads(); + } +#pragma unroll + for (int c = 0; c < 4; ++c) { + const int col = n0 + c0 + c; + if (row < a.m and col < a.n) a.out[static_cast(row) * a.n + col] = acc[c] * a.global; + } +} + +// A decode round, one column a thread with ROWS rows in flight: no LDS, no sixteen-row stage, and two chunks of codes +// prefetched so the column's reads are pipelined. A group's 16 inputs fold in the small block's order and the group +// scale lands on the group's partial, so a row's bits are the same either way. +// +// The prefetch is not decoration. With a guard clause and no prefetch this card software-pipelines nothing - 22 VGPRs +// against 33, and 2.6x slower - so the loads are stated here instead. Requires k a multiple of kNvChunk, which the +// launch checks before choosing this path. +template +__device__ __forceinline__ void nvfp4_columns(Nvfp4 a) { + const int col = blockIdx.x * blockDim.x + threadIdx.x; + if (col >= a.n) return; + const int groups = a.k / a.group; + const int chunks = a.k / kNvChunk; + const hip_bfloat16* x = static_cast(a.x); + const uint32_t* w = a.words + static_cast(col) * (a.k / 8); + const long long sbase = static_cast(col) * groups; + + uint32_t hold[DEPTH][kNvWords]; +#pragma unroll + for (int d = 0; d < DEPTH; ++d) { +#pragma unroll + for (int wd = 0; wd < kNvWords; ++wd) hold[d][wd] = d < chunks ? w[d * kNvWords + wd] : 0u; + } + + float acc[ROWS]; +#pragma unroll + for (int r = 0; r < ROWS; ++r) acc[r] = 0.f; + + for (int ci = 0; ci < chunks; ++ci) { + const int kc = ci * kNvChunk; + uint32_t cur[kNvWords]; +#pragma unroll + for (int wd = 0; wd < kNvWords; ++wd) cur[wd] = hold[0][wd]; +#pragma unroll + for (int d = 0; d + 1 < DEPTH; ++d) { +#pragma unroll + for (int wd = 0; wd < kNvWords; ++wd) hold[d][wd] = hold[d + 1][wd]; + } + const int fetch = ci + DEPTH; + if (fetch < chunks) { +#pragma unroll + for (int wd = 0; wd < kNvWords; ++wd) hold[DEPTH - 1][wd] = w[fetch * kNvWords + wd]; + } +#pragma unroll + for (int g = 0; g < kNvChunk / 16; ++g) { + float q[ROWS]; +#pragma unroll + for (int r = 0; r < ROWS; ++r) q[r] = 0.f; +#pragma unroll + for (int j = 0; j < 16; ++j) { + const int code = g * 16 + j; + const float lvl = nvfp4_level(cur[code / 8] >> (4 * (code % 8))); +#pragma unroll + for (int r = 0; r < ROWS; ++r) { + q[r] = fmaf(lvl, static_cast(x[static_cast(r) * a.k + kc + code]), q[r]); + } + } + const int gi = kc / 16 + g < groups ? kc / 16 + g : groups - 1; + const float scale = nvfp4_scale(a.scale, sbase + gi); +#pragma unroll + for (int r = 0; r < ROWS; ++r) acc[r] = fmaf(q[r], scale, acc[r]); + } + } +#pragma unroll + for (int r = 0; r < ROWS; ++r) { + a.out[static_cast(r) * a.n + col] = acc[r] * a.global; + } +} + +} // namespace rocm +} // namespace tf + +// This path serves bf16 activations only: the engine refuses an fp16 build for a ModelOpt checkpoint. +extern "C" __global__ void __launch_bounds__(256) tf_nvfp4_gemm(tf::rocm::Nvfp4 a) { + if (a.m >= tf::rocm::kNvSmallM) tf::rocm::nvfp4_block(a); + else tf::rocm::nvfp4_small(a); +} + +// A decode round on nvfp4_columns: the launch picks tf_nvfp4_col to match a.m exactly, so no row is padded to +// sixteen and a row's offset is a constant. These are separate entry points rather than a switch inside one kernel: +// the kernel contract records resources an entry point, and a branch on a.m would keep every variant's registers. +extern "C" __global__ void __launch_bounds__(256) tf_nvfp4_col1(tf::rocm::Nvfp4 a) { + tf::rocm::nvfp4_columns<1, tf::rocm::kNvDepth>(a); +} +extern "C" __global__ void __launch_bounds__(256) tf_nvfp4_col2(tf::rocm::Nvfp4 a) { + tf::rocm::nvfp4_columns<2, tf::rocm::kNvDepth>(a); +} +extern "C" __global__ void __launch_bounds__(256) tf_nvfp4_col3(tf::rocm::Nvfp4 a) { + tf::rocm::nvfp4_columns<3, tf::rocm::kNvDepth>(a); +} +extern "C" __global__ void __launch_bounds__(256) tf_nvfp4_col4(tf::rocm::Nvfp4 a) { + tf::rocm::nvfp4_columns<4, tf::rocm::kNvDepth>(a); +} diff --git a/zig/kernels/hip/tiles/dot2_tiles.hip b/zig/kernels/hip/tiles/dot2_tiles.hip index c3828bb6c6d..2fa5c9b87a1 100644 --- a/zig/kernels/hip/tiles/dot2_tiles.hip +++ b/zig/kernels/hip/tiles/dot2_tiles.hip @@ -7,6 +7,8 @@ #include "tiles/matrix_gemm.hpp" #include "quant/mlx_tiles.hpp" #include "quant/dense_tiles.hpp" +#include "quant/nvfp4_tiles.hpp" +#include "quant/fp8_tiles.hpp" // ModelOpt FP8 and NVFP4 products, each a 64-row tile and a 16-row decode block namespace tf { namespace rocm { diff --git a/zig/src/core/contract/hip_records.zig b/zig/src/core/contract/hip_records.zig index 03e9821e456..759b868708e 100644 --- a/zig/src/core/contract/hip_records.zig +++ b/zig/src/core/contract/hip_records.zig @@ -498,7 +498,7 @@ const own_records = [own_count]Record{ pub const records = own_records ++ @import("hip_records_stream.zig").records ++ @import("hip_records_router.zig").records ++ @import("hip_records_item.zig").records ++ @import("hip_records_qwen3.zig").records ++ @import("hip_records_columns.zig").records ++ - @import("hip_records_vision.zig").records ++ @import("hip_records_dense_text.zig").records ++ @import("hip_records_families.zig").all ++ @import("hip_records_skew.zig").records ++ @import("hip_records_gdn.zig").records; + @import("hip_records_vision.zig").records ++ @import("hip_records_dense_text.zig").records ++ @import("hip_records_families.zig").all ++ @import("hip_records_skew.zig").records ++ @import("hip_records_gdn.zig").records ++ @import("hip_records_nvfp4.zig").records; /// Gate 5's planted HIP controls: a launch past its __launch_bounds__, and 72 KiB of LDS where a workgroup has 64. pub const controls = [2]Record{ diff --git a/zig/src/core/contract/hip_records_families.zig b/zig/src/core/contract/hip_records_families.zig index 96151923483..db8188ac9e7 100644 --- a/zig/src/core/contract/hip_records_families.zig +++ b/zig/src/core/contract/hip_records_families.zig @@ -40,6 +40,7 @@ test "HIP record counts stay pinned in their owning files" { @import("hip_records_inkling2_dense.zig").records.len, @import("hip_records_inkling2_logits.zig").records.len, @import("hip_records_item.zig").records.len, + @import("hip_records_nvfp4.zig").records.len, @import("hip_records_joint.zig").records.len, @import("hip_records_lighton_ocr.zig").records.len, @import("hip_records_pair.zig").records.len, diff --git a/zig/src/core/contract/hip_records_nvfp4.zig b/zig/src/core/contract/hip_records_nvfp4.zig new file mode 100644 index 00000000000..e8e6df4e297 --- /dev/null +++ b/zig/src/core/contract/hip_records_nvfp4.zig @@ -0,0 +1,59 @@ +//! Measured resources of the ModelOpt products on gfx1030, gfx1100, gfx1151 and gfx1201, in limits.rdna order. +const Record = @import("hip_records.zig").Record; + +pub const records = [6]Record{ + .{ + .launch = .{ .name = "ModelOpt NVFP4 product", .symbol = "tf_nvfp4_gemm", .image = "affine_tiles", .threads = 256 }, + .usage = .{ + .{ .vgprs = 138, .sgprs = 38, .lds = 16384, .private = 0, .bound = 256, .wave = 32 }, + .{ .vgprs = 144, .sgprs = 38, .lds = 16384, .private = 0, .bound = 256, .wave = 32 }, + .{ .vgprs = 144, .sgprs = 38, .lds = 16384, .private = 0, .bound = 256, .wave = 32 }, + .{ .vgprs = 143, .sgprs = 36, .lds = 16384, .private = 0, .bound = 256, .wave = 32 }, + }, + }, + .{ + .launch = .{ .name = "ModelOpt FP8 product", .symbol = "tf_fp8_gemm", .image = "affine_tiles", .threads = 256 }, + .usage = .{ + .{ .vgprs = 58, .sgprs = 49, .lds = 18432, .private = 0, .bound = 256, .wave = 32 }, + .{ .vgprs = 56, .sgprs = 49, .lds = 18432, .private = 0, .bound = 256, .wave = 32 }, + .{ .vgprs = 56, .sgprs = 49, .lds = 18432, .private = 0, .bound = 256, .wave = 32 }, + .{ .vgprs = 58, .sgprs = 48, .lds = 18432, .private = 0, .bound = 256, .wave = 32 }, + }, + }, + .{ + .launch = .{ .name = "ModelOpt NVFP4 decode, one row", .symbol = "tf_nvfp4_col1", .image = "affine_tiles", .threads = 256 }, + .usage = .{ + .{ .vgprs = 130, .sgprs = 22, .lds = 0, .private = 0, .bound = 256, .wave = 32 }, + .{ .vgprs = 138, .sgprs = 22, .lds = 0, .private = 0, .bound = 256, .wave = 32 }, + .{ .vgprs = 138, .sgprs = 22, .lds = 0, .private = 0, .bound = 256, .wave = 32 }, + .{ .vgprs = 138, .sgprs = 23, .lds = 0, .private = 0, .bound = 256, .wave = 32 }, + }, + }, + .{ + .launch = .{ .name = "ModelOpt NVFP4 decode, two rows", .symbol = "tf_nvfp4_col2", .image = "affine_tiles", .threads = 256 }, + .usage = .{ + .{ .vgprs = 164, .sgprs = 26, .lds = 0, .private = 0, .bound = 256, .wave = 32 }, + .{ .vgprs = 165, .sgprs = 26, .lds = 0, .private = 0, .bound = 256, .wave = 32 }, + .{ .vgprs = 165, .sgprs = 26, .lds = 0, .private = 0, .bound = 256, .wave = 32 }, + .{ .vgprs = 164, .sgprs = 28, .lds = 0, .private = 0, .bound = 256, .wave = 32 }, + }, + }, + .{ + .launch = .{ .name = "ModelOpt NVFP4 decode, three rows", .symbol = "tf_nvfp4_col3", .image = "affine_tiles", .threads = 256 }, + .usage = .{ + .{ .vgprs = 148, .sgprs = 31, .lds = 0, .private = 0, .bound = 256, .wave = 32 }, + .{ .vgprs = 145, .sgprs = 30, .lds = 0, .private = 0, .bound = 256, .wave = 32 }, + .{ .vgprs = 145, .sgprs = 30, .lds = 0, .private = 0, .bound = 256, .wave = 32 }, + .{ .vgprs = 147, .sgprs = 34, .lds = 0, .private = 0, .bound = 256, .wave = 32 }, + }, + }, + .{ + .launch = .{ .name = "ModelOpt NVFP4 decode, four rows", .symbol = "tf_nvfp4_col4", .image = "affine_tiles", .threads = 256 }, + .usage = .{ + .{ .vgprs = 121, .sgprs = 32, .lds = 0, .private = 0, .bound = 256, .wave = 32 }, + .{ .vgprs = 141, .sgprs = 32, .lds = 0, .private = 0, .bound = 256, .wave = 32 }, + .{ .vgprs = 141, .sgprs = 32, .lds = 0, .private = 0, .bound = 256, .wave = 32 }, + .{ .vgprs = 144, .sgprs = 38, .lds = 0, .private = 0, .bound = 256, .wave = 32 }, + }, + }, +}; diff --git a/zig/src/core/fixtures/modelopt_fp8/config.json b/zig/src/core/fixtures/modelopt_fp8/config.json new file mode 100644 index 00000000000..807f99c1114 --- /dev/null +++ b/zig/src/core/fixtures/modelopt_fp8/config.json @@ -0,0 +1,53 @@ +{ + "architectures": [ + "Qwen3_5ForConditionalGeneration" + ], + "dtype": "bfloat16", + "model_type": "qwen3_5", + "tie_word_embeddings": false, + "text_config": { + "hidden_size": 4096, + "intermediate_size": 12288, + "num_hidden_layers": 8, + "num_attention_heads": 16, + "num_key_value_heads": 4, + "head_dim": 256, + "linear_num_key_heads": 16, + "linear_num_value_heads": 32, + "linear_key_head_dim": 128, + "linear_value_head_dim": 128, + "linear_conv_kernel_dim": 4, + "vocab_size": 248320, + "full_attention_interval": 4, + "layer_types": [ + "linear_attention", + "linear_attention", + "linear_attention", + "full_attention", + "linear_attention", + "linear_attention", + "linear_attention", + "full_attention" + ], + "rms_norm_eps": 1e-06, + "rope_parameters": { + "rope_theta": 10000000, + "partial_rotary_factor": 0.25 + }, + "eos_token_id": 248044 + }, + "quantization_config": { + "quant_algo": "FP8", + "kv_cache_scheme": null, + "ignore": [ + "lm_head", + "model.language_model.embed_tokens", + "model.language_model.layers.0.mlp.gate" + ], + "producer": { + "name": "modelopt", + "version": "0.47.0" + }, + "quant_method": "modelopt" + } +} diff --git a/zig/src/core/fixtures/modelopt_int4/config.json b/zig/src/core/fixtures/modelopt_int4/config.json new file mode 100644 index 00000000000..e471caf995b --- /dev/null +++ b/zig/src/core/fixtures/modelopt_int4/config.json @@ -0,0 +1,48 @@ +{ + "architectures": [ + "Qwen3_5ForConditionalGeneration" + ], + "dtype": "bfloat16", + "model_type": "qwen3_5", + "tie_word_embeddings": false, + "text_config": { + "hidden_size": 4096, + "intermediate_size": 12288, + "num_hidden_layers": 8, + "num_attention_heads": 16, + "num_key_value_heads": 4, + "head_dim": 256, + "linear_num_key_heads": 16, + "linear_num_value_heads": 32, + "linear_key_head_dim": 128, + "linear_value_head_dim": 128, + "linear_conv_kernel_dim": 4, + "vocab_size": 248320, + "full_attention_interval": 4, + "layer_types": [ + "linear_attention", + "linear_attention", + "linear_attention", + "full_attention", + "linear_attention", + "linear_attention", + "linear_attention", + "full_attention" + ], + "rms_norm_eps": 1e-06, + "rope_parameters": { + "rope_theta": 10000000, + "partial_rotary_factor": 0.25 + }, + "eos_token_id": 248044 + }, + "quantization_config": { + "quant_algo": "INT4_AWQ", + "kv_cache_scheme": null, + "producer": { + "name": "modelopt", + "version": "0.47.0" + }, + "quant_method": "modelopt" + } +} \ No newline at end of file diff --git a/zig/src/core/modelopt.zig b/zig/src/core/modelopt.zig index 8a3951df906..4162ddb1f55 100644 --- a/zig/src/core/modelopt.zig +++ b/zig/src/core/modelopt.zig @@ -74,7 +74,14 @@ pub const Why = struct { } }; -/// config.json's quantization_config (top level, else text_config's) checked as ModelOpt NVFP4. +/// The single formats this engine reads as stored: NVFP4, checked as ModelOpt writes it, and plain FP8, per tensor. +fn singleFormat(algo: []const u8, q: std.json.ObjectMap, why: *Why) !void { + if (std.ascii.eqlIgnoreCase(algo, "FP8")) return; + // the grouped FP8 formats are named MXFP8 and FP8_PB_WO and stay refusals by module + try nvfp4(q, why); +} + +/// config.json's quantization_config (top level, else text_config's): a single format this engine reads as stored. pub fn admit(gpa: std.mem.Allocator, config_json: []const u8, why: *Why) !void { var arena = std.heap.ArenaAllocator.init(gpa); defer arena.deinit(); @@ -83,7 +90,7 @@ pub fn admit(gpa: std.mem.Allocator, config_json: []const u8, why: *Why) !void { why.set("config.json has no ModelOpt quantization_config", .{}); return error.NotModelOpt; }; - try nvfp4(q, why); + try singleFormat(text(q.get("quant_algo")) orelse "", q, why); } /// `admit`'s check, with MIXED_PRECISION read: a quantized_layers entry no `Recipe` names is refused by its module. @@ -97,8 +104,9 @@ pub fn admitRecipes(gpa: std.mem.Allocator, config_json: []const u8, why: *Why) }; var r: Recipes = .{ .arena = .init(gpa) }; errdefer r.deinit(); - if (!std.ascii.eqlIgnoreCase(text(q.get("quant_algo")) orelse "", "MIXED_PRECISION")) { - try nvfp4(q, why); + const single = text(q.get("quant_algo")) orelse ""; + if (!std.ascii.eqlIgnoreCase(single, "MIXED_PRECISION")) { + try singleFormat(single, q, why); return r; } r.mixed = true; @@ -231,11 +239,6 @@ fn expectRefused(json: []const u8, err: anyerror, word: []const u8) !void { test "other ModelOpt formats, and configs without ModelOpt, are refused by name" { try expectRefused("{\"text_config\": {}}", error.NotModelOpt, "no ModelOpt"); try expectRefused("{\"quantization_config\": {\"quant_method\": \"exl3\"}}", error.NotModelOpt, "no ModelOpt"); - try expectRefused( - "{\"quantization_config\": {\"quant_method\": \"modelopt\", \"quant_algo\": \"FP8\"}}", - error.UnsupportedQuant, - "ModelOpt FP8", - ); // MIXED_PRECISION (the AXL re-pack) is refused for now try expectRefused( "{\"quantization_config\": {\"quant_method\": \"modelopt\", \"quant_algo\": \"MIXED_PRECISION\"}}", @@ -294,6 +297,22 @@ test "a single-format NVFP4 config declares no recipes" { try std.testing.expectEqual(@as(u32, 0), r.modules.count()); } +test "a single-format ModelOpt FP8 config is admitted: plain FP8 is read as stored, no recipes" { + var why: Why = .{}; + // both entry points read the one fixture, so neither can drift from the other on what a single format is + try admit(std.testing.allocator, @embedFile("fixtures/modelopt_fp8/config.json"), &why); + var r = try admitRecipes(std.testing.allocator, @embedFile("fixtures/modelopt_fp8/config.json"), &why); + defer r.deinit(); + try std.testing.expect(!r.mixed); + try std.testing.expectEqual(@as(u32, 0), r.modules.count()); +} + +test "a single-format config of an algorithm this engine does not read is still refused by name" { + var why: Why = .{}; + try std.testing.expectError(error.UnsupportedQuant, admitRecipes(std.testing.allocator, @embedFile("fixtures/modelopt_int4/config.json"), &why)); + try std.testing.expect(std.mem.indexOf(u8, why.text(), "INT4_AWQ") != null); +} + /// admitRecipes() must refuse a MIXED_PRECISION config of these `layers` as unsupported, its reason naming `word`. fn expectRecipesRefused(comptime layers: []const u8, word: []const u8) !void { const json = "{\"quantization_config\": {\"quant_method\": \"modelopt\", \"quant_algo\": \"MIXED_PRECISION\"" ++ @@ -333,9 +352,12 @@ test "recipes this engine does not read are refused by module" { \\, "quantized_layers": {"m.f": {"quant_algo": "FP8", "group_size": 128}} , "m.f: FP8"); var why: Why = .{}; - try std.testing.expectError(error.UnsupportedQuant, admitRecipes(std.testing.allocator, + // a single-format FP8 config is read as stored, like single-format NVFP4: no module declares a recipe + var fp8 = try admitRecipes(std.testing.allocator, \\{"quantization_config": {"quant_method": "modelopt", "quant_algo": "FP8"}} - , &why)); + , &why); + defer fp8.deinit(); + try std.testing.expect(!fp8.mixed and fp8.modules.count() == 0); var r = try admitRecipes(std.testing.allocator, \\{"quantization_config": {"quant_method": "modelopt", "quant_algo": "MIXED_PRECISION", "quantized_layers": \\ {"m.experts": {"quant_algo": "NVFP4", "group_size": 16}}}} diff --git a/zig/src/core/quant/fp8.zig b/zig/src/core/quant/fp8.zig index f28169ddae9..91946fb9e09 100644 --- a/zig/src/core/quant/fp8.zig +++ b/zig/src/core/quant/fp8.zig @@ -9,6 +9,11 @@ const Why = @import("../modelopt.zig").Why; /// Rows and columns one scale_inv entry covers. pub const block = 128; +/// What a kernel reads of a ModelOpt FP8 projection: the codes' address and the projection's one scale. +pub const Matrix = struct { codes: u64, scale: u64 }; + +pub const View = struct { n: u32, k: u32, matrix: Matrix }; + /// An e4m3 code's value; 0x7f and 0xff are NaN, as the GPU's conversion reads them. pub fn e4m3(b: u8) f64 { if (b & 0x7f == 0x7f) return std.math.nan(f64); diff --git a/zig/src/core/quant/nvfp4.zig b/zig/src/core/quant/nvfp4.zig index 3ec81cf2a8a..ee67fb3f40c 100644 --- a/zig/src/core/quant/nvfp4.zig +++ b/zig/src/core/quant/nvfp4.zig @@ -1,9 +1,13 @@ -//! ModelOpt NVFP4 weights (e2m1 codes, an e4m3 scale every 16 inputs, a global scale) on the host: fp64 references. +//! ModelOpt NVFP4 as stored: e2m1 codes, an E4M3 scale every 16 inputs, one global scale, and the f64 reference. + const std = @import("std"); const types = @import("types.zig"); +const slice = @import("slice.zig"); +const convert = @import("convert.zig"); const fp8 = @import("fp8.zig"); const Tensor = types.Tensor; +const Allocator = std.mem.Allocator; /// Inputs one e4m3 scale covers. pub const group = 16; @@ -14,18 +18,158 @@ pub fn e2m1(n: u8) f64 { return (if (n & 8 != 0) @as(f64, -1) else 1) * mag[n & 7]; } -/// As stored: `weight` u8 [..., N, K / 2] (even columns low nibbles), `scale` e4m3 [..., N, K / 16], `global` a matrix. +/// As stored: `weight` u8 [..., N, K / 2] (even columns low nibbles), `scale` BF16 [..., N, K / 16], one global scale. pub const Host = struct { weight: Tensor, scale: Tensor, global: []const f32 }; +fn name(buf: []u8, key: []const u8, suffix: []const u8) ?[]const u8 { + return std.fmt.bufPrint(buf, "{s}{s}", .{ key, suffix }) catch null; +} + +fn refuse(key: []const u8, what: []const u8) error{UnexpectedTensor} { + return types.refuse(key, what); +} + +/// Why these tensors cannot be this format, or null when they can: checked without a log, as `bf16.unfit` is. +pub fn unfit(w: Tensor, s: Tensor, g: Tensor) ?[]const u8 { + if (w.dtype != .u8 or w.rank != 2) return "an NVFP4 weight is U8 [N, K/2]"; + const n = w.shape[0]; + // checked before any product: an empty tensor's header passes with any width ([0, 2^63] holds no bytes) + const k = std.math.mul(usize, w.shape[1], 2) catch return "an NVFP4 weight's K is past 2^64"; + if (n > std.math.maxInt(u32) or k > std.math.maxInt(u32)) return "an NVFP4 weight's N and K are each below 2^32"; + if (k % 32 != 0) return "an NVFP4 weight's K is a multiple of 32 (eights of codes, groups of 16)"; + if (s.rank != 2 or s.shape[0] != n) return "NVFP4 scales are [N, K/16]"; + const sk = std.math.mul(usize, s.shape[1], group) catch return "NVFP4 scales are [N, K/16]"; + if (sk != k) return "NVFP4 scales are [N, K/16]"; + if (g.numel() != 1 or g.dtype != .f32) return "NVFP4's second scale is one F32"; + const global = convert.load(.f32, g.bytes, 0); + if (!std.math.isFinite(global) or global == 0) return "NVFP4's second scale is zero, infinite or nan"; + switch (s.dtype) { + .f8_e4m3 => for (0..s.numel()) |i| { + if (s.bytes[i] & 0x7f == 0x7f) return "an NVFP4 scale is E4M3 nan"; + }, + else => return "NVFP4 scales are E4M3, which is what ModelOpt writes and the 16-bit table holds", + } + return null; +} + +/// `key`'s projection as stored, its group table widened; any other dtype, rank or value is refused by name. +pub fn read(a: Allocator, t: anytype, key: []const u8) !Host { + var b: [3][320]u8 = undefined; + const wn = name(&b[0], key, ".weight") orelse return error.UnexpectedTensor; + const sn = name(&b[1], key, ".weight_scale") orelse return error.UnexpectedTensor; + const gn = name(&b[2], key, ".weight_scale_2") orelse return error.UnexpectedTensor; + const w = try t.get(wn); + const s = try t.get(sn); + const g = try t.get(gn); + if (unfit(w, s, g)) |why| return refuse(wn, why); + const one = try a.alloc(f32, 1); + one[0] = convert.load(.f32, g.bytes, 0); + return .{ .weight = w, .scale = try widened(a, s), .global = one }; +} + +/// The group table as the kernel reads it: E4M3's values as BF16 (exact: three mantissa bits fit seven). +fn widened(a: Allocator, s: Tensor) !Tensor { + const out = try a.alloc(u16, s.numel()); + for (out, 0..) |*o, i| { + const value: f32 = @floatCast(fp8.e4m3(s.bytes[i])); + o.* = @truncate(@as(u32, @bitCast(value)) >> 16); + } + return .{ .dtype = .bf16, .rank = s.rank, .shape = s.shape, .bytes = std.mem.sliceAsBytes(out) }; +} + +pub fn rows(h: Host) usize { + return h.weight.shape[0]; +} + +pub fn bytes(h: Host) usize { + return h.weight.bytes.len + h.scale.bytes.len + @sizeOf(f32) * h.global.len; +} + +/// Inputs of the projection. +fn inputs(h: Host) usize { + return 2 * h.weight.shape[1]; +} + +/// Columns [from, to) of K, copied: a cut on an even input (a byte of codes) and a group boundary. +fn cols(a: Allocator, p: Host, from: usize, to: usize) slice.Error!Host { + if (from % 2 != 0 or to % 2 != 0 or from % group != 0 or to % group != 0) return error.UnevenSplit; + return .{ + .weight = try slice.takeCols(a, p.weight, from / 2, to / 2), + .scale = try slice.takeCols(a, p.scale, from / group, to / group), + .global = p.global, + }; +} + +/// Both halves along K, copied (K a multiple of 32). +pub fn halves(a: Allocator, p: Host) slice.Error![2]Host { + const k = inputs(p); + if (k % 32 != 0) return error.UnevenSplit; + return .{ try cols(a, p, 0, k / 2), try cols(a, p, k / 2, k) }; +} + +pub fn sliceRows(a: Allocator, p: Host, spans: []const slice.Span) slice.Error!Host { + return .{ .weight = try slice.takeRows(a, p.weight, spans), .scale = try slice.takeRows(a, p.scale, spans), .global = p.global }; +} + +pub fn sliceCols(a: Allocator, p: Host, r: slice.Rank, what: []const u8) slice.Error!Host { + const width = try slice.even(inputs(p), r.world, what); + return cols(a, p, r.rank * width, (r.rank + 1) * width); +} + +/// An uploaded projection: the checkpoint's codes and group table on the device, the global scale a number. +pub const Device = struct { weight: types.Buf, scale: types.Buf, global: f32 }; + +/// The tensors as stored: this format keeps its layout, as MLX's does. +pub fn upload(u: types.Uploader, h: Host) !Device { + if (h.global.len != 1) return error.UnexpectedTensor; // a stack's experts carry a global each + return .{ .weight = try u.tensor(h.weight), .scale = try u.tensor(h.scale), .global = h.global[0] }; +} + +/// What the kernels read of an NVFP4 projection: the codes' address, the group table's and the global scale. +pub const Matrix = struct { codes: u64, scale: u64, tables: types.Tables, global: f32 }; + +pub const View = struct { n: u32, k: u32, matrix: Matrix }; + +fn tableKind(dtype: types.DType) error{UnsupportedTables}!types.Tables { + return switch (dtype) { + .f32 => .f32, + .bf16 => .bf16, + .f16 => .f16, + else => error.UnsupportedTables, + }; +} + +/// The projection's (N, K) and addresses; a stack is refused: its experts carry a global scale each. +pub fn view(d: Device, stacked: bool) error{UnsupportedTables}!View { + if (stacked or d.weight.dtype != .u8 or d.weight.rank != 2) return error.UnsupportedTables; + const k = std.math.mul(usize, d.weight.shape[1], 2) catch return error.UnsupportedTables; + const sk = std.math.mul(usize, d.scale.shape[1], group) catch return error.UnsupportedTables; + if (d.scale.rank != 2 or d.scale.shape[0] != d.weight.shape[0] or sk != k) return error.UnsupportedTables; + return .{ + .n = std.math.cast(u32, d.weight.shape[0]) orelse return error.UnsupportedTables, + .k = std.math.cast(u32, k) orelse return error.UnsupportedTables, + .matrix = .{ .codes = d.weight.ptr, .scale = d.scale.ptr, .tables = try tableKind(d.scale.dtype), .global = d.global }, + }; +} + /// Weights of a projection: its rows (a stack's leading dimensions folded) by K. pub fn elements(h: Host) usize { return h.weight.numel() * 2; } +/// A group table entry as fp64, in whichever form the host holds it. +fn scaleOf(h: Host, i: usize) f64 { + return switch (h.scale.dtype) { + .f8_e4m3 => fp8.e4m3(h.scale.bytes[i]), + else => convert.load(h.scale.dtype, h.scale.bytes, i), + }; +} + /// fp64 dequantization of every row of `h` (a stack's leading dimensions folded), code * scale * global, into `out`. pub fn reference(h: Host, out: []f64) error{UnexpectedTensor}!void { const rank = h.weight.rank; - if (rank < 2 or rank > h.weight.shape.len or h.scale.rank != rank or h.weight.dtype != .u8 or h.scale.dtype != .f8_e4m3) return error.UnexpectedTensor; + if (rank < 2 or rank > h.weight.shape.len or h.scale.rank != rank or h.weight.dtype != .u8) return error.UnexpectedTensor; + if (h.scale.dtype != .f8_e4m3 and !convert.tableDtype(h.scale.dtype)) return error.UnexpectedTensor; const n = h.weight.shape[rank - 2]; const k = h.weight.shape[rank - 1] * 2; if (n == 0 or k == 0) return error.UnexpectedTensor; @@ -37,10 +181,14 @@ pub fn reference(h: Host, out: []f64) error{UnexpectedTensor}!void { const row = e * n + r; const byte = h.weight.bytes[row * (k / 2) + c / 2]; const nib: u8 = if (c & 1 == 0) byte & 0xF else byte >> 4; - out[row * k + c] = e2m1(nib) * fp8.e4m3(h.scale.bytes[row * (k / group) + c / group]) * h.global[e]; + out[row * k + c] = e2m1(nib) * scaleOf(h, row * (k / group) + c / group) * h.global[e]; }; } +fn parsed(a: Allocator, text: []const u8) !std.json.ObjectMap { + return (try std.json.parseFromSliceLeaky(std.json.Value, a, text, .{})).object; +} + test "an NVFP4 stack against hand-decoded values" { // two experts of [1, 32]: two scale groups a row; byte 0 holds columns 0 (low) and 1 (high) var codes: [2 * 16]u8 = @splat(0); @@ -75,3 +223,109 @@ test "a reference refuses mismatched expert stacks" { var out: [32]f64 = undefined; try std.testing.expectError(error.UnexpectedTensor, reference(h, &out)); } + +const Fake = struct { + w: Tensor, + s: Tensor, + g: Tensor, + + pub fn get(f: *const Fake, key: []const u8) !Tensor { + if (std.mem.endsWith(u8, key, ".weight")) return f.w; + if (std.mem.endsWith(u8, key, ".weight_scale_2")) return f.g; + if (std.mem.endsWith(u8, key, ".weight_scale")) return f.s; + return error.MissingTensor; + } + + pub fn has(f: *const Fake, key: []const u8) bool { + _ = f; + return std.mem.endsWith(u8, key, ".weight_scale_2"); + } +}; + +test "a projection is read as stored, its E4M3 table widened exactly; a bad scale is unfit" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var codes: [4 * 16]u8 = @splat(0); + codes[0] = 0x21; // row 0, inputs 0 and 1: e2m1 1 (+0.5) and 2 (+1.0) + const scales = [_]u8{ 0x38, 0x38, 0x38, 0x38, 0x38, 0x38, 0x38, 0x40 }; // [4, 2]: 1s, then 2 in the last row + const g = [_]f32{0.5}; + const t: Fake = .{ + .w = .{ .dtype = .u8, .rank = 2, .shape = .{ 4, 16, 1, 1, 1 }, .bytes = &codes }, + .s = .{ .dtype = .f8_e4m3, .rank = 2, .shape = .{ 4, 2, 1, 1, 1 }, .bytes = &scales }, + .g = .{ .dtype = .f32, .rank = 1, .shape = .{ 1, 1, 1, 1, 1 }, .bytes = std.mem.sliceAsBytes(&g) }, + }; + try std.testing.expect(unfit(t.w, t.s, t.g) == null); + const h = try read(a, &t, "x"); + try std.testing.expectEqual(types.DType.bf16, h.scale.dtype); + try std.testing.expectEqual(@as(f32, 0.5), h.global[0]); + try std.testing.expectEqual(@as(usize, 4), rows(h)); + try std.testing.expectEqual(@as(usize, 64 + 8 * 2 + 4), bytes(h)); + var out: [128]f64 = undefined; + try reference(h, &out); + try std.testing.expectEqual(@as(f64, 0.25), out[0]); + try std.testing.expectEqual(@as(f64, 0.5), out[1]); + try std.testing.expectEqual(@as(f64, 0), out[2]); + + var nan = scales; + nan[7] = 0x7f; + try std.testing.expect(unfit(t.w, .{ .dtype = .f8_e4m3, .rank = 2, .shape = .{ 4, 2, 1, 1, 1 }, .bytes = &nan }, t.g) != null); + const zero = [_]f32{0}; + try std.testing.expect(unfit(t.w, t.s, .{ .dtype = .f32, .rank = 1, .shape = .{ 1, 1, 1, 1, 1 }, .bytes = std.mem.sliceAsBytes(&zero) }) != null); + var f32_table = [_]f32{ 1.0, 1.0 }; + try std.testing.expect(unfit(t.w, .{ .dtype = .f32, .rank = 2, .shape = .{ 4, 2, 1, 1, 1 }, .bytes = std.mem.sliceAsBytes(&f32_table) }, t.g) != null); + var short = t.w; // K = 16, but K is a multiple of 32 + short.shape = .{ 4, 8, 1, 1, 1 }; + try std.testing.expect(unfit(short, t.s, t.g) != null); +} + +test "halves cut the codes on a byte and the scales on a group" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var codes: [2 * 32]u8 = undefined; + for (&codes, 0..) |*c, i| c.* = @truncate(i); + const scales = [_]u8{ 0x38, 0x38, 0x38, 0x38, 0x38, 0x38, 0x38, 0x38 }; // [2, 4] + const g = [_]f32{1}; + const h: Host = .{ + .weight = .{ .dtype = .u8, .rank = 2, .shape = .{ 2, 32, 1, 1, 1 }, .bytes = &codes }, + .scale = .{ .dtype = .f8_e4m3, .rank = 2, .shape = .{ 2, 4, 1, 1, 1 }, .bytes = &scales }, + .global = &g, + }; + const pair = try halves(a, h); + try std.testing.expectEqualSlices(u8, codes[0..16], pair[0].weight.bytes[0..16]); + try std.testing.expectEqualSlices(u8, codes[32..48], pair[0].weight.bytes[16..32]); + try std.testing.expectEqualSlices(u8, codes[16..32], pair[1].weight.bytes[0..16]); + try std.testing.expectEqualSlices(u8, codes[48..64], pair[1].weight.bytes[16..32]); + try std.testing.expectEqual(@as(usize, 2), pair[0].scale.shape[1]); + try std.testing.expectEqual(@as(usize, 64), elements(pair[0])); +} + +test "a view is the codes' and table's addresses and the global scale; a stack is refused" { + const d: Device = .{ + .weight = .{ .ptr = 4096, .len = 64, .dtype = .u8, .rank = 2, .shape = .{ 4, 16, 1, 1, 1 } }, + .scale = .{ .ptr = 8192, .len = 16, .dtype = .bf16, .rank = 2, .shape = .{ 4, 2, 1, 1, 1 } }, + .global = 0.25, + }; + const v = try view(d, false); + try std.testing.expectEqual(@as(u32, 4), v.n); + try std.testing.expectEqual(@as(u32, 32), v.k); + try std.testing.expectEqual(@as(u64, 4096), v.matrix.codes); + try std.testing.expectEqual(@as(u64, 8192), v.matrix.scale); + try std.testing.expectEqual(types.Tables.bf16, v.matrix.tables); + try std.testing.expectEqual(@as(f32, 0.25), v.matrix.global); + try std.testing.expectError(error.UnsupportedTables, view(d, true)); + var narrow = d; + narrow.scale.shape = .{ 4, 1, 1, 1, 1 }; // K/16 of 1 does not cover K = 32 + try std.testing.expectError(error.UnsupportedTables, view(narrow, false)); +} + +test "a stack of experts is refused: a global scale is one a projection" { + var codes: [2 * 8 * 16]u8 = @splat(0); + const scales: [2 * 8 * 2]u8 = @splat(0x38); + const g = [_]f32{ 1, 1 }; + const w: Tensor = .{ .dtype = .u8, .rank = 3, .shape = .{ 2, 8, 16, 1, 1 }, .bytes = &codes }; + const s: Tensor = .{ .dtype = .f8_e4m3, .rank = 3, .shape = .{ 2, 8, 2, 1, 1 }, .bytes = &scales }; + const gg: Tensor = .{ .dtype = .f32, .rank = 1, .shape = .{ 2, 1, 1, 1, 1 }, .bytes = std.mem.sliceAsBytes(&g) }; + try std.testing.expect(unfit(w, s, gg) != null); +} diff --git a/zig/src/core/quant/quant.zig b/zig/src/core/quant/quant.zig index 1a6b47234b3..59220281972 100644 --- a/zig/src/core/quant/quant.zig +++ b/zig/src/core/quant/quant.zig @@ -12,8 +12,9 @@ pub const dense = @import("dense.zig"); /// BF16 as stored, an unquantized checkpoint's: the family opts in (`bf16.detect`), so `read_order` never offers it. pub const bf16 = @import("bf16.zig"); pub const experts = @import("experts.zig"); -/// FP8 and NVFP4 values and fp64 references; host only (no Format: their kernels' layouts are each backend's). +/// FP8 values and fp64 references; host only (no Format: kernel layouts are each backend's). pub const fp8 = @import("fp8.zig"); +/// ModelOpt NVFP4: e2m1 codes, an e4m3 scale a 16 inputs and one global scale, kept as stored on the device. pub const nvfp4 = @import("nvfp4.zig"); /// AutoGPTQ v1 weights (4-bit symmetric groups of 128) and their fp64 reference; host only, as `fp8`. pub const gptq = @import("gptq.zig"); @@ -182,14 +183,22 @@ pub const Projection = struct { k: u32, /// Split along K: the product stays fp32, one rank's share of a sum. partial: bool = false, - handle: Handle, - - pub fn format(p: Projection) Format { - return std.meta.activeTag(p.handle); + /// The shared format's handle; null for a ModelOpt NVFP4 projection, whose matrix is `nvfp4`. + handle: ?Handle = null, + /// ModelOpt NVFP4's matrix, a format the engine names: core keeps no such `Format`. + nvfp4: ?nvfp4.Matrix = null, + /// ModelOpt FP8's matrix, the same way. + fp8: ?fp8.Matrix = null, + + pub fn format(p: Projection) ?Format { + const h = p.handle orelse return null; + return switch (h) { + inline else => |_, tag| tag, + }; } - pub fn decoder(p: Projection) Decoder { - return switch (p.format()) { + pub fn decoder(p: Projection) ?Decoder { + return switch (p.format() orelse return null) { inline else => |f| Module(f).decoder, }; } diff --git a/zig/src/families/qwen3_5/backend/hip/engine/engine.zig b/zig/src/families/qwen3_5/backend/hip/engine/engine.zig index 122a30d64c8..387892b6ff9 100644 --- a/zig/src/families/qwen3_5/backend/hip/engine/engine.zig +++ b/zig/src/families/qwen3_5/backend/hip/engine/engine.zig @@ -19,6 +19,7 @@ const scratch = @import("scratch.zig"); const mtp = @import("mtp.zig"); const admission = hip.admission; const prefix = @import("prefix.zig"); +const prompt_poll = @import("prompt_poll.zig"); const plan = @import("../forward/plan.zig"); const config = @import("../../../weights/config.zig"); const table = @import("../../../weights/table.zig"); @@ -66,20 +67,22 @@ fn gib(bytes: usize) f64 { return @as(f64, @floatFromInt(bytes)) / (1 << 30); } -/// The checkpoint's device bytes, near enough to refuse before reading: bf16 text, doubled when `chat` widens it. +/// The checkpoint's device bytes, near enough to refuse before reading: a ModelOpt one's own, or bf16 text. fn checkpointBytes(gpa: std.mem.Allocator, io: std.Io, dir: []const u8, chat: bool) !u64 { var c = try config.Config.read(gpa, io, dir); defer c.deinit(); + // a ModelOpt checkpoint keeps its codes as stored and widens its group tables: count what the device holds + if (c.modelopt) return table.deviceBytesAt(gpa, io, dir); if (c.quant != .bf16) return admission.weightBytes(io, dir); - const bf16 = try table.textBytes(gpa, io, dir); + const bf16 = try table.textBytes(gpa, io, dir, c.spec.mtp_layers); return if (chat) 2 * bf16 else bf16; } -/// A bf16 checkpoint served for chat (chatBf16): its projections run widened, on the row-invariant dense kernels. -fn chatCheckpoint(gpa: std.mem.Allocator, io: std.Io, dir: []const u8) bool { - var c = config.Config.read(gpa, io, dir) catch return false; +/// What the checkpoint's config says about serving it: chat widening (chatBf16), and ModelOpt's own products. +fn shape(gpa: std.mem.Allocator, io: std.Io, dir: []const u8) struct { chat: bool, modelopt: bool } { + var c = config.Config.read(gpa, io, dir) catch return .{ .chat = false, .modelopt = false }; defer c.deinit(); - return c.quant == .bf16 and chatBf16(gpa, io, dir); + return .{ .chat = c.quant == .bf16 and chatBf16(gpa, io, dir), .modelopt = c.modelopt }; } /// Whether a bf16 checkpoint serves chat: an image tower the engine reads and no joint_head_config.json (Clef's). @@ -113,6 +116,8 @@ pub const Engine = struct { pub const Rows = lane_round.Rows; gpa: std.mem.Allocator, + /// A ModelOpt checkpoint: its text layers decode in flight, its vision tower reads dense. + modelopt: bool = false, driver: hip.Runtime, ctx: hip.Context, lib: hip.Launcher, @@ -199,23 +204,30 @@ pub const Engine = struct { errdefer if (group != null) e.comm.close(); _ = try steps.done(.{ 0, 0 }, .first); // a chat checkpoint's drafted and concurrent rounds equal its solo ones: rocBLAS products vary with rows - const chat = chatCheckpoint(gpa, io, dir); + const ckpt = shape(gpa, io, dir); + const chat = ckpt.chat; + e.modelopt = ckpt.modelopt; if (o.preflight) |pf| { // a rank loads its share of the checkpoint, near enough to refuse before reading it pf.* = .{ .pool = try e.budget(io), .held = hip.usage(false).device, .weights = try checkpointBytes(gpa, io, dir, chat) / o.world }; if (seen) |limits| pf.weights += try vision.Vision.bytes(try vision.Vision.config(gpa, io, dir), limits); if (pf.weights > pf.pool.room(pf.held)) return error.WeightsDoNotFit; } + // a ModelOpt checkpoint's own products: bf16 activations and one rank, refused before its shards are read + if (e.modelopt and (e.act != .bf16 or o.world > 1)) { + std.log.err("a ModelOpt checkpoint needs bf16 activations on one rank", .{}); + return error.UnsupportedQuantization; + } _ = try steps.done(.{ 0, 0 }, .first); e.weights = try weights.Model.loadRankWith(gpa, io, &e.driver, dir, group, chat); errdefer e.weights.deinit(); - if (e.plain() or chat) { - // a bf16 checkpoint's products (rocBLAS, or widened for chat): one rank, not qualified under graphs - if (e.act != .bf16) { + if (e.plain() or chat or e.modelopt) { + // bf16 products (rocBLAS, or the dense kernels a ModelOpt or chat checkpoint reads): no graphs + if ((e.plain() or chat) and e.act != .bf16) { std.log.err("a bf16 checkpoint needs bf16 activations; this GPU computes in fp16", .{}); return error.UnsupportedQuantization; } - if (o.world > 1) { + if ((e.plain() or chat) and o.world > 1) { std.log.err("a bf16 checkpoint runs on one rank", .{}); return error.UnsupportedQuantization; } @@ -266,6 +278,7 @@ pub const Engine = struct { errdefer e.pool.deinit(); e.round = try lane_round.State.init(e); errdefer e.round.deinit(e); + // rocBLAS serves an unquantized checkpoint's projections alone: a ModelOpt one reads dense if (e.plain()) { e.workspace = try hip.DeviceBuffer.alloc(&e.driver, hip.blas.workspace_bytes); e.blas = hip.blas.Blas.open(e.stream) catch |err| { @@ -300,7 +313,10 @@ pub const Engine = struct { /// The checkpoint's projections are BF16 as stored (an unquantized HF checkpoint): rocBLAS runs them. pub fn plain(e: *const Engine) bool { - return e.weights.embed == .bf16; + return switch (e.weights.embed) { + .core => |d| std.meta.activeTag(d) == .bf16, + .nvfp4, .fp8 => false, + }; } fn closeBlas(e: *Engine) void { @@ -487,24 +503,13 @@ pub const Engine = struct { } /// Asked at a long prompt's layer edges once the layer before is done: true drains, then `error.Cancelled`. - pub const Cancel = @import("lanes").stream.CancelCheck; - - const Poll = struct { - edges: @import("hip_serve").cancel.Layers(hip.Stream, hip.Event), - cancel: Cancel, + pub const Cancel = prompt_poll.Cancel; - fn layer(ctx: *anyopaque, _: usize, _: hip.ops.Tensor, _: usize) anyerror!void { - const p: *Poll = @ptrCast(@alignCast(ctx)); - try p.edges.edge(p.cancel.ptr, p.cancel.check); - } - }; + const Poll = prompt_poll.Poll; /// The pass over `len` rows polling the cancel after each layer; null where it cannot stop (a short prompt, or tp). fn poll(e: *Engine, cancel: ?Cancel, len: usize, p: *Poll) ?fwd.Trace { - const c = cancel orelse return null; - if (!prefix.pollsLayers(e.o.world, len)) return null; - p.* = .{ .edges = .{ .stream = e.stream, .events = e.edge_events }, .cancel = c }; - return .{ .ctx = p, .layer = Poll.layer, .reads = false }; + return prompt_poll.trace(e.o.world, e.stream, e.edge_events, cancel, len, p); } /// What each prompt pass reads of its final rows: a cut none, the prompt's last chunk its last row, a readout all. 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 e5d7a0942c9..edd394939e7 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 @@ -300,7 +300,7 @@ test "a readout begins at row 0 with no cuts while the tree would resume a plain test "a test's cut rows fix every piece end, which the recorder lists" { var e: @import("engine.zig").Engine = undefined; e.o = .{ .cut_rows = 300 }; - e.weights.embed = .{ .mlx = undefined }; // a quantized checkpoint: the chunk rule reads only the format + e.weights.embed = .{ .core = .{ .mlx = undefined } }; // a quantized checkpoint: the chunk rule reads only the format var h: source.Hip = undefined; h.gpa = T.allocator; h.e = &e; @@ -348,7 +348,7 @@ test "a readout's piece stays the chunk while another lane decodes; a plain prom test "alone a plain prompt takes the engine's prompt rows; a readout keeps the chunk, a decoder's neighbour the fill rows" { var e: @import("engine.zig").Engine = undefined; e.o = .{ .prompt_rows = 4096, .policy = .{ .prefill_step = 4096 } }; // as a lone gfx1151 opens - e.weights.embed = .{ .mlx = undefined }; + e.weights.embed = .{ .core = .{ .mlx = undefined } }; var h: source.Hip = undefined; h.gpa = T.allocator; h.e = &e; @@ -374,7 +374,7 @@ test "alone a plain prompt takes the engine's prompt rows; a readout keeps the c test "a bf16 checkpoint, and an engine opened for longer passes than its policy's rows, keep the chunk" { var e: @import("engine.zig").Engine = undefined; e.o = .{ .prompt_rows = 4096, .policy = .{ .prefill_step = 4096 } }; - e.weights.embed = .{ .bf16 = undefined }; // rocBLAS products: their bits follow the rows of a piece + e.weights.embed = .{ .core = .{ .bf16 = undefined } }; // rocBLAS products: their bits follow the rows of a piece var h: source.Hip = undefined; h.gpa = T.allocator; h.e = &e; @@ -385,7 +385,7 @@ test "a bf16 checkpoint, and an engine opened for longer passes than its policy' plain.readout = null; try T.expectEqual(prefix.chunk, try h.reach(&plain, 0, 9000)); e.o = .{ .prompt_rows = 9000 }; // a check's longest prompt under the plain policy - e.weights.embed = .{ .mlx = undefined }; + e.weights.embed = .{ .core = .{ .mlx = undefined } }; try T.expectEqual(prefix.chunk, try h.reach(&plain, 0, 9000)); } diff --git a/zig/src/families/qwen3_5/backend/hip/engine/mtp.zig b/zig/src/families/qwen3_5/backend/hip/engine/mtp.zig index c595d0e49db..4d5bbdb25c1 100644 --- a/zig/src/families/qwen3_5/backend/hip/engine/mtp.zig +++ b/zig/src/families/qwen3_5/backend/hip/engine/mtp.zig @@ -127,10 +127,15 @@ pub const Head = struct { return h; } + /// This head's launches on `s`: the engine's library and arena, and the activation kind. + fn ops(m: *const view.Model, lib: *const hip.Launcher, s: hip.abi.Stream, arena: *hip.Arena) Ops { + return .{ .l = lib, .bf16 = m.act == .bf16, .stream = s, .arena = arena }; + } + /// The arena a batch of `cap` chains takes at full depth, counted on the counting stream. fn scratch(h: *Head, lib: *const hip.Launcher, m: *const view.Model) !usize { var arena = hip.Arena.counting(); - const o: Ops = .{ .l = lib, .bf16 = m.act == .bf16, .stream = hip.counting, .arena = &arena }; + const o: Ops = ops(m, lib, hip.counting, &arena); try h.steps(o, m, h.draft_head, h.cap, max_depth, true); return arena.peak; } @@ -171,7 +176,7 @@ pub const Head = struct { } fn batch(h: *Head, lib: *const hip.Launcher, stream: hip.Stream, m: *const view.Model, jobs: []Job, graphs: bool) !void { - const o: Ops = .{ .l = lib, .bf16 = m.act == .bf16, .stream = stream.handle, .arena = &h.arena }; + const o: Ops = ops(m, lib, stream.handle, &h.arena); h.arena.reset(); const rows = jobs.len; const at = h.layout(); @@ -258,7 +263,7 @@ pub const Head = struct { const ids = if (n == 0) dev else drafts - 4 * h.cap; const logits = try h.step(o, m, head, cur, ids, rows, dev + at.slots + 4 * n, dev + at.pos + 4 * h.cap * n, n); try o.argmaxRows(logits, rows, head.n, drafts); - if (cut and n + 1 < most) try o.tokenProb(logits, rows, head.n, 0, dev + at.probs + 4 * h.cap * n); + try if (cut and n + 1 < most) o.tokenProb(logits, rows, head.n, 0, dev + at.probs + 4 * h.cap * n); cur = .{ .ptr = h.last, .kind = m.act }; } } 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 66c30716938..fedd40d6bf0 100644 --- a/zig/src/families/qwen3_5/backend/hip/engine/native.zig +++ b/zig/src/families/qwen3_5/backend/hip/engine/native.zig @@ -12,26 +12,32 @@ const state = @import("../forward/state.zig"); const worker = @import("worker.zig"); const hip_lanes = @import("hip_lanes.zig"); const joint = @import("joint_readout.zig"); +const refusals = @import("native_refusals.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: { - const widths = @import("core").quant.mlx.bit_widths; - var out: [widths.len * 3][]const u8 = undefined; - for (widths, 0..) |bits, i| for ([_]u16{ 32, 64, 128 }, 0..) |g, j| { - out[3 * i + j] = std.fmt.comptimePrint("mlx-q{d}g{d}", .{ bits, g }); +/// MLX affine widths; a dense checkpoint adds ModelOpt's two, the sparse family none. +fn formatsOf(comptime type_name: []const u8) []const []const u8 { + return comptime blk: { + const widths = @import("core").quant.mlx.bit_widths; + const named = [_][]const u8{ "modelopt-nvfp4", "modelopt-fp8" }; + const extra: usize = if (std.mem.eql(u8, type_name, "qwen3_5")) named.len else 0; + var out: [widths.len * 3 + extra][]const u8 = undefined; + for (widths, 0..) |bits, i| for ([_]u16{ 32, 64, 128 }, 0..) |g, j| { + out[3 * i + j] = std.fmt.comptimePrint("mlx-q{d}g{d}", .{ bits, g }); + }; + for (named[0..extra], 0..) |f, k| out[widths.len * 3 + k] = f; + const done = out; + break :blk &done; }; - const done = out; - break :blk &done; -}; +} /// The dense and the sparse checkpoints are two registry entries over one engine. pub fn Native(comptime type_name: []const u8) type { return struct { pub const model_type = type_name; - pub const formats = mlx_formats; + pub const formats = formatsOf(type_name); /// BF16 serves decisions only, with a joint schema head (joint_head_config.json); chat refuses it. pub const decision_formats: []const []const u8 = &.{"bf16"}; /// Positions a stream holds when neither --context nor the checkpoint's config names a window. @@ -66,50 +72,14 @@ pub const Loaded = struct { }; /// A flag or a resource the engine cannot take: `problem` says why. -pub const Refused = error{Refused}; - -fn refuse(a: std.mem.Allocator, problem: *[]const u8, comptime fmt: []const u8, args: anytype) Refused { - problem.* = std.fmt.allocPrint(a, fmt, args) catch fmt; - return error.Refused; -} - -fn gibs(bytes: usize) f64 { - return @as(f64, @floatFromInt(bytes)) / (1 << 30); -} - -/// Why `dir` cannot be served: BF16 Qwen3.5 serves only with its joint head, and the head only on the BF16 weights. -fn decisionOnly(a: std.mem.Allocator, gpa: std.mem.Allocator, io: std.Io, dir: []const u8) ?[]const u8 { - // 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(); - const head = joint.present(io, a, dir); - if (c.quant != .bf16 and head) { - const what = "the joint schema head needs the BF16 checkpoint"; - return std.fmt.allocPrint(a, "{s}: {s} is quantized ({t})", .{ what, dir, c.quant }) catch what; - } - if (c.quant != .bf16 or head) return null; - if (engine.chatBf16(gpa, io, dir)) return null; // an image checkpoint: a tower the engine reads, no joint head - const what = "BF16 Qwen3.5 serves as a decision backbone only"; - return std.fmt.allocPrint(a, "{s}: {s} has no joint_head_config.json", .{ what, dir }) catch what; -} - -/// Why a Clef checkpoint cannot open under tensor parallelism: its head runs on one rank, so no rank opens it. -fn oneRank(a: std.mem.Allocator, io: std.Io, dir: []const u8, o: Options) ?[]const u8 { - if (o.world <= 1 or !joint.present(io, a, dir)) return null; - return "the joint schema head serves on one rank; drop --tp"; -} +pub const Refused = refusals.Refused; -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; -} +const refuse = refusals.refuse; +const gibs = refusals.gibs; +const decisionOnly = refusals.decisionOnly; +const oneRank = refusals.oneRank; +const bf16_drafter = refusals.bf16_drafter; +const bf16Drafter = refusals.bf16Drafter; /// 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 { @@ -449,9 +419,10 @@ fn openJoint(a: std.mem.Allocator, gpa: std.mem.Allocator, e: *Engine, loaded: j errdefer if (owned) w.deinit(); const blas = if (e.blas) |*b| b else return steps.refuseAll(a, problem, "the joint schema head needs rocBLAS", .{}); const head_rows = e.model().head; - if (head_rows.format() != .bf16) return steps.refuseAll(a, problem, "the joint schema head reads a BF16 lm_head", .{}); + const head_format = head_rows.format(); + if (head_format == null or head_format.? != .bf16) return steps.refuseAll(a, problem, "the joint schema head reads a BF16 lm_head", .{}); const before = hip.usage(false).device; - const head = hip.joint_schema.Head.init(gpa, &e.driver, &e.lib, blas, w.weights, bounds, head_rows.handle.bf16.weight, head_rows.n) catch |err| + const head = hip.joint_schema.Head.init(gpa, &e.driver, &e.lib, blas, w.weights, bounds, head_rows.handle.?.bf16.weight, head_rows.n) catch |err| return steps.refuseAll(a, problem, "the joint schema head cannot start ({s})", .{@errorName(err)}); owned = false; errdefer head.deinit(); @@ -510,6 +481,17 @@ test "a bf16 checkpoint without a joint head is refused as decision-only, an MLX for (Native(kind).formats) |format| try std.testing.expect(!std.mem.eql(u8, format, "bf16")); try std.testing.expectEqualStrings("bf16", Native(kind).decision_formats[0]); } + // the sparse family refuses a ModelOpt checkpoint, so it offers neither format; the dense one offers both + var moe_offered: usize = 0; + for (Native("qwen3_5_moe").formats) |format| if (std.mem.startsWith(u8, format, "modelopt-")) { + moe_offered += 1; + }; + try std.testing.expectEqual(@as(usize, 0), moe_offered); + var dense_offered: usize = 0; + for (Native("qwen3_5").formats) |format| if (std.mem.startsWith(u8, format, "modelopt-")) { + dense_offered += 1; + }; + try std.testing.expectEqual(@as(usize, 2), dense_offered); const mlx = try std.mem.replaceOwned(u8, a, text, "\"tie_word_embeddings\": false,", "\"tie_word_embeddings\": false, \"quantization\": {\"group_size\": 64, \"bits\": 4, \"mode\": \"affine\"},"); try tmp.dir.writeFile(io, .{ .sub_path = "config.json", .data = mlx }); // a quantized checkpoint that ships the head would open as a text model: refused by name instead diff --git a/zig/src/families/qwen3_5/backend/hip/engine/native_refusals.zig b/zig/src/families/qwen3_5/backend/hip/engine/native_refusals.zig new file mode 100644 index 00000000000..21ea420d040 --- /dev/null +++ b/zig/src/families/qwen3_5/backend/hip/engine/native_refusals.zig @@ -0,0 +1,55 @@ +//! Why the native HIP engine cannot serve a checkpoint, decided from its config before any shard is read. + +const std = @import("std"); +const engine = @import("engine.zig"); +const joint = @import("joint_readout.zig"); +const config = @import("../../../weights/config.zig"); +const serve = @import("hip_serve"); + +const Options = serve.Options; + +/// A flag or a resource the engine cannot take: `problem` says why. +pub const Refused = error{Refused}; + +pub fn refuse(a: std.mem.Allocator, problem: *[]const u8, comptime fmt: []const u8, args: anytype) Refused { + problem.* = std.fmt.allocPrint(a, fmt, args) catch fmt; + return error.Refused; +} + +pub fn gibs(bytes: usize) f64 { + return @as(f64, @floatFromInt(bytes)) / (1 << 30); +} + +/// Why `dir` cannot be served: BF16 Qwen3.5 serves only with its joint head, and the head only on the BF16 weights. +pub fn decisionOnly(a: std.mem.Allocator, gpa: std.mem.Allocator, io: std.Io, dir: []const u8) ?[]const u8 { + // 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(); + const head = joint.present(io, a, dir); + if (c.quant != .bf16 and head) { + const what = "the joint schema head needs the BF16 checkpoint"; + return std.fmt.allocPrint(a, "{s}: {s} is quantized ({t})", .{ what, dir, c.quant }) catch what; + } + if (c.quant != .bf16 or c.modelopt or head) return null; + if (engine.chatBf16(gpa, io, dir)) return null; // an image checkpoint: a tower the engine reads, no joint head + const what = "BF16 Qwen3.5 serves as a decision backbone only"; + return std.fmt.allocPrint(a, "{s}: {s} has no joint_head_config.json", .{ what, dir }) catch what; +} + +/// Why a Clef checkpoint cannot open under tensor parallelism: its head runs on one rank, so no rank opens it. +pub fn oneRank(a: std.mem.Allocator, io: std.Io, dir: []const u8, o: Options) ?[]const u8 { + if (o.world <= 1 or !joint.present(io, a, dir)) return null; + return "the joint schema head serves on one rank; drop --tp"; +} + +pub 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. +pub 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; +} diff --git a/zig/src/families/qwen3_5/backend/hip/engine/prompt_poll.zig b/zig/src/families/qwen3_5/backend/hip/engine/prompt_poll.zig new file mode 100644 index 00000000000..c3802382603 --- /dev/null +++ b/zig/src/families/qwen3_5/backend/hip/engine/prompt_poll.zig @@ -0,0 +1,27 @@ +//! The layer-cancel poll a prompt pass carries: one edge per layer, where a pass can stop. + +const hip = @import("hip"); +const lanes = @import("lanes"); +const fwd = @import("../forward/forward.zig"); +const prefix = @import("prefix.zig"); + +/// Asked at a long prompt's layer edges once the layer before is done: true drains, then `error.Cancelled`. +pub const Cancel = lanes.stream.CancelCheck; + +pub const Poll = struct { + edges: @import("hip_serve").cancel.Layers(hip.Stream, hip.Event), + cancel: Cancel, + + fn layer(ctx: *anyopaque, _: usize, _: hip.ops.Tensor, _: usize) anyerror!void { + const p: *Poll = @ptrCast(@alignCast(ctx)); + try p.edges.edge(p.cancel.ptr, p.cancel.check); + } +}; + +/// The pass over `len` rows polling the cancel after each layer; null where it cannot stop (a short prompt, or tp). +pub fn trace(world: usize, stream: hip.Stream, events: [2]hip.Event, cancel: ?Cancel, len: usize, p: *Poll) ?fwd.Trace { + const c = cancel orelse return null; + if (!prefix.pollsLayers(world, len)) return null; + p.* = .{ .edges = .{ .stream = stream, .events = events }, .cancel = c }; + return .{ .ctx = p, .layer = Poll.layer, .reads = false }; +} diff --git a/zig/src/families/qwen3_5/backend/hip/forward/prompt_tail.zig b/zig/src/families/qwen3_5/backend/hip/forward/prompt_tail.zig index e3665eca67b..083d28042af 100644 --- a/zig/src/families/qwen3_5/backend/hip/forward/prompt_tail.zig +++ b/zig/src/families/qwen3_5/backend/hip/forward/prompt_tail.zig @@ -60,7 +60,7 @@ fn densePastKeys(f: view.Full) bool { } fn isDense(p: view.Projection) bool { - return p.handle == .dense; + return p.format() == .dense; } test "qwen3_5 hip prompt tail: an open chunk keeps its last tile, or only its keys when nothing reads it" { diff --git a/zig/src/families/qwen3_5/backend/hip/model/bridge.zig b/zig/src/families/qwen3_5/backend/hip/model/bridge.zig index fc65975e152..5931faf8640 100644 --- a/zig/src/families/qwen3_5/backend/hip/model/bridge.zig +++ b/zig/src/families/qwen3_5/backend/hip/model/bridge.zig @@ -2,6 +2,7 @@ const std = @import("std"); const hip = @import("hip"); +const quant = @import("core").quant; const view = @import("view.zig"); const weights = @import("weights.zig"); @@ -9,7 +10,29 @@ pub const Error = error{UnsupportedTables} || hip.Error || std.mem.Allocator.Err /// A projection (N, K) from its uploaded tensors, in whichever format they are. pub fn projection(p: weights.Projection) Error!view.Projection { - return hip.quant.view(p, false); + return switch (p) { + .core => |d| hip.quant.view(d, false), + .nvfp4 => |d| blk: { + const v = try quant.nvfp4.view(d, false); + break :blk .{ .n = v.n, .k = v.k, .nvfp4 = v.matrix }; + }, + .fp8 => |d| blk: { + if (d.weight.rank != 2) return error.UnsupportedTables; + break :blk .{ + .n = @intCast(d.weight.dim(0)), + .k = @intCast(d.weight.dim(1)), + .fp8 = .{ .codes = d.weight.ptr, .scale = d.scale.ptr }, + }; + }, + }; +} + +/// A stack's view: only the shared formats hold one (an NVFP4 stack is refused, a global scale an expert). +fn coreView(p: weights.Projection, stacked: bool) Error!view.Projection { + return switch (p) { + .core => |d| hip.quant.view(d, stacked), + .nvfp4, .fp8 => error.UnsupportedTables, + }; } /// A projection split along K: its fp32 output is one rank's share of the sum. @@ -30,8 +53,8 @@ pub fn mlpView(m: weights.Mlp, sliced: bool) Error!view.Mlp { .rows = r.router.dim(0), .remap = if (r.remap) |b| b.ptr else 0, .experts = .{ - .fused = try hip.quant.view(r.experts.fused, true), - .down = try hip.quant.view(r.experts.down, true), + .fused = try coreView(r.experts.fused, true), + .down = try coreView(r.experts.down, true), .count = r.experts.count, .width = r.experts.width, .dims = r.experts.dims, diff --git a/zig/src/families/qwen3_5/backend/hip/model/weights.zig b/zig/src/families/qwen3_5/backend/hip/model/weights.zig index 0c2291f4ea0..25d199e71db 100644 --- a/zig/src/families/qwen3_5/backend/hip/model/weights.zig +++ b/zig/src/families/qwen3_5/backend/hip/model/weights.zig @@ -15,8 +15,15 @@ pub const DType = table.DType; /// One uploaded tensor: its device address and the element type and shape of the bytes there. pub const Buf = quant.Buf; -/// A projection on the device in its format: the tensors as that format keeps them. -pub const Projection = quant.Device; +/// A projection on the device in its format: the shared formats' tensors, or ModelOpt's NVFP4 ones. +pub const Projection = union(enum) { + core: quant.Device, + nvfp4: quant.nvfp4.Device, + fp8: Fp8, +}; + +/// A ModelOpt FP8 projection on the device: its E4M3 codes and the one scale, as stored. +pub const Fp8 = struct { weight: Buf, scale: Buf }; /// A layer's E + 1 experts, the shared one last; `fused` is gate then up per expert when `gated`. pub const Experts = struct { @@ -93,7 +100,25 @@ const Uploader = struct { } fn projection(u: Uploader, p: host.Projection) !Projection { - return quant.upload(u.up.uploader(), p); + const up = u.up.uploader(); + return switch (p) { + .mlx => |x| .{ .core = try quant.upload(up, .{ .mlx = x }) }, + .dense => |x| .{ .core = try quant.upload(up, .{ .dense = x }) }, + .bf16 => |x| .{ .core = try quant.upload(up, .{ .bf16 = x }) }, + .nvfp4 => |x| .{ .nvfp4 = try quant.nvfp4.upload(up, x) }, + .fp8 => |x| .{ .fp8 = try fp8(u, x) }, + }; + } + + fn fp8(u: Uploader, p: host.StoredFp8) !Fp8 { + const up = u.up.uploader(); + const scale: Tensor = .{ .dtype = .f32, .rank = 1, .shape = .{ p.scale.len, 1, 1, 1, 1 }, .bytes = std.mem.sliceAsBytes(p.scale) }; + return .{ .weight = try up.tensor(p.weight), .scale = try up.tensor(scale) }; + } + + /// A stack of experts: core's routed experts keep the shared formats' tensors. + fn expert(u: Uploader, h: quant.Host) !Projection { + return .{ .core = try quant.upload(u.up.uploader(), h) }; } fn mlp(u: Uploader, m: host.Mlp) !Mlp { @@ -105,9 +130,9 @@ const Uploader = struct { .router = try u.tensor(r.router), .rows32 = try u.tensor(r.rows32), .experts = .{ - .fused = try u.projection(e.fused), + .fused = try u.expert(e.fused), .gated = e.gated, - .down = try u.projection(e.down), + .down = try u.expert(e.down), .width = e.width, .dims = e.dims, .count = e.count, diff --git a/zig/src/families/qwen3_5/hip.zig b/zig/src/families/qwen3_5/hip.zig index ec61e5f7b1d..3e12ffbed39 100644 --- a/zig/src/families/qwen3_5/hip.zig +++ b/zig/src/families/qwen3_5/hip.zig @@ -47,6 +47,7 @@ test { _ = @import("weights/projection.zig"); _ = @import("weights/checkpoint_test.zig"); _ = @import("weights/checkpoint_hf_test.zig"); + _ = @import("weights/mtp_source_test.zig"); _ = @import("weights/real_test.zig"); _ = view; _ = moe; diff --git a/zig/src/families/qwen3_5/loader.zig b/zig/src/families/qwen3_5/loader.zig index 86b372f6cb4..d2cda071d8d 100644 --- a/zig/src/families/qwen3_5/loader.zig +++ b/zig/src/families/qwen3_5/loader.zig @@ -16,6 +16,8 @@ test { _ = @import("weights/projection.zig"); _ = @import("weights/checkpoint_test.zig"); _ = @import("weights/checkpoint_hf_test.zig"); + _ = @import("weights/nvfp4_shape_test.zig"); + _ = @import("weights/mtp_source_test.zig"); _ = @import("weights/real_test.zig"); @import("std").testing.refAllDecls(slicing); _ = @import("config.zig"); diff --git a/zig/src/families/qwen3_5/weights/checkpoint.zig b/zig/src/families/qwen3_5/weights/checkpoint.zig index c84748d6e6b..092ff382a98 100644 --- a/zig/src/families/qwen3_5/weights/checkpoint.zig +++ b/zig/src/families/qwen3_5/weights/checkpoint.zig @@ -33,6 +33,12 @@ pub const Names = struct { } }; +/// Why a ModelOpt checkpoint is not read here, or null: its routed experts are a stack with one global scale an expert. +pub fn modelOptExpertsWhy(cfg: *const config.Config) ?[]const u8 { + if (cfg.modelopt and cfg.spec.experts > 0) return "a ModelOpt checkpoint with routed experts is not read on this backend: its experts carry a global scale each"; + return null; +} + pub const Checkpoint = struct { gpa: std.mem.Allocator, io: std.Io, @@ -40,28 +46,38 @@ pub const Checkpoint = struct { files: table.Files, main: Table, names: Names, + /// The single MTP source selection, shared with preflight's byte accounting; null when there is no head. + mtp_source: ?table.MtpSource, /// Reads config.json and maps the model's own safetensors files. pub fn open(gpa: std.mem.Allocator, io: std.Io, dir: []const u8) !Checkpoint { var cfg = try config.Config.read(gpa, io, dir); errdefer cfg.deinit(); + if (modelOptExpertsWhy(&cfg)) |why| { + std.log.err("{s}", .{why}); + return error.UnsupportedQuantization; + } const bf16 = cfg.quant == .bf16; // a bf16 checkpoint's own shards are the index's: side files (a joint head) stay out of the table - var files = try if (bf16) table.Files.indexed(gpa, io, dir) else table.Files.list(gpa, io, dir); + var files = try if (bf16) table.Files.indexed(gpa, io, dir, cfg.modelopt) else table.Files.list(gpa, io, dir); errdefer files.deinit(); if (files.model.len == 0) return error.NoSafetensors; var main = try Table.open(gpa, io, files.model, "", cfg.quant); errdefer main.close(io); + main.modelopt = cfg.modelopt; const names = Names.of(&main); if (names.refusal(bf16)) |why| { std.log.err("{s}", .{why}); return error.UnexpectedTensor; } - if (bf16) if (mixed(&main, names)) |key| { + // ModelOpt stores FP8 and NVFP4 tensors beside bf16 ones; the loader reads both as stored. + if (bf16 and !cfg.modelopt) if (mixed(&main, names)) |key| { std.log.err("{s}: {t} in a bf16 checkpoint, whose text tensors are all BF16", .{ key, (main.peek(key) orelse unreachable).dtype }); return error.UnexpectedTensor; }; - return .{ .gpa = gpa, .io = io, .config = cfg, .files = files, .main = main, .names = names }; + // one selection, from one presence test: preflight calls the same function for its byte count + const mtp_source = try files.mtpSource(gpa, io); + return .{ .gpa = gpa, .io = io, .config = cfg, .files = files, .main = main, .names = names, .mtp_source = mtp_source }; } pub fn close(c: *Checkpoint) void { @@ -164,40 +180,41 @@ pub const Checkpoint = struct { return .{ .arena = arena, .body = body }; } - /// The MTP layer from `mtp*.safetensors` or the model's own shards; null when absent. + /// The MTP layer from an MTP side file or the model's own shards; null when absent. pub fn mtp(c: *const Checkpoint) !?host.Mtp { - if (c.config.quant == .bf16) { - if (c.spec().mtp_layers == 0) return null; - std.log.err("a bf16 checkpoint's MTP head is not read: its config declares {d} MTP layers", .{c.spec().mtp_layers}); - return error.UnexpectedTensor; + if (c.config.quant == .bf16 and !c.config.modelopt) { + if (c.spec().mtp_layers > 0) { + std.log.err("a bf16 checkpoint's MTP head is not read: its config declares {d} MTP layers", .{c.spec().mtp_layers}); + return error.UnexpectedTensor; + } } - const side = c.files.side; - const shards = if (side.len > 0) side else c.files.model; - if (shards.len == 0) return null; - const own = c.main.has("mtp.norm_e.weight") or c.main.has("mtp.pre_fc_norm_embedding.weight"); + // The source was selected in `open`; preflight selects the same one for `deviceBytes`. + const source = c.mtp_source orelse return null; var opened: ?Table = null; errdefer if (opened) |*o| o.close(c.io); - var t = &c.main; - if (side.len > 0 or !own) { - opened = try Table.open(c.gpa, c.io, shards, "language_model.", c.config.quant); + var t: *const Table = &c.main; + if (!source.main) { + var cand = try Table.open(c.gpa, c.io, source.paths, "language_model.", c.config.quant); + cand.modelopt = c.config.modelopt; + // `mtpSource` chose these files for a first norm; a table without one is not the head it chose + if (!cand.hasMtpNorm()) { + cand.close(c.io); + return error.MtpHeadWithoutNorm; + } + opened = cand; t = &opened.?; } - if (side.len == 0 and !t.has("mtp.norm_e.weight") and !t.has("mtp.pre_fc_norm_embedding.weight")) { - if (opened) |*o| o.close(c.io); - return null; - } var arena: std.heap.ArenaAllocator = .init(c.gpa); errdefer arena.deinit(); var m = try readMtp(arena.allocator(), t, c.spec()); m.arena = arena; m.owned = opened; m.io = c.io; - // the head read through `opened`: the main table's own `mtp` names and a side file's leftovers - if (opened != null) { + if (!source.main) { c.main.skip("mtp."); c.main.skip("language_model.mtp."); } - if (side.len > 0 and opened.?.unused() != 0) return error.UnusedQwen35Tensors; + if (source.side) if (opened) |*o| if (o.unused() != 0) return error.UnusedQwen35Tensors; return m; } diff --git a/zig/src/families/qwen3_5/weights/checkpoint_hf_test.zig b/zig/src/families/qwen3_5/weights/checkpoint_hf_test.zig index 316af33aad6..d78d0b82467 100644 --- a/zig/src/families/qwen3_5/weights/checkpoint_hf_test.zig +++ b/zig/src/families/qwen3_5/weights/checkpoint_hf_test.zig @@ -4,6 +4,9 @@ const std = @import("std"); const checkpoint = @import("checkpoint.zig"); const table = @import("table.zig"); const projection = @import("projection.zig"); +const host = @import("host.zig"); +const modelopt = @import("modelopt.zig"); +const qcfg = @import("config.zig"); const convert = @import("core").quant.convert; const io = std.testing.io; @@ -26,6 +29,8 @@ const File = struct { names: std.ArrayList([]const u8) = .empty, header: std.ArrayList(u8) = .empty, data: std.ArrayList(u8) = .empty, + /// Plant E4M3's 0x7f NaN as the first code of every FP8 tensor written after this is set. + fp8_nan: bool = false, fn init() File { return .{ .arena = .init(gpa) }; @@ -47,6 +52,12 @@ const File = struct { const v: f32 = 0.25 + @as(f32, @floatFromInt((seed +% @as(u16, @truncate(i * 7))) % 64)) / 256.0; if (std.mem.eql(u8, dtype, "F32")) { try f.data.appendSlice(a, &std.mem.toBytes(v)); + } else if (std.mem.eql(u8, dtype, "U8")) { + try f.data.append(a, @truncate(seed +% @as(u16, @truncate(i)))); + } else if (std.mem.eql(u8, dtype, "F8_E4M3")) { + // codes below 0x7f are finite E4M3: only 0x7f and 0xff are nan, so the planted one is the only refusal + const code: u8 = @intCast((seed +% @as(u16, @truncate(i))) % 0x7f); + try f.data.append(a, if (f.fp8_nan and i == 0) 0x7f else code); } else try f.data.appendSlice(a, &std.mem.toBytes(convert.bf16(v))); } try f.header.print(a, "{s}\"{s}\":{{\"dtype\":\"{s}\",\"shape\":[", .{ if (f.names.items.len > 0) "," else "", name, dtype }); @@ -67,8 +78,20 @@ const File = struct { } }; -/// What to plant: one text tensor as F32, the conv weight in another layout, or an index entry of a vision-only shard. -const Plant = struct { f32_tensor: ?[]const u8 = null, conv: []const usize = &.{ 96, 1, 4 }, vision_shard: bool = false }; +/// What to plant: an F32 text tensor, a conv in another layout, a vision-only shard entry, or ModelOpt's format. +const Plant = struct { + f32_tensor: ?[]const u8 = null, + conv: []const usize = &.{ 96, 1, 4 }, + vision_shard: bool = false, + modelopt: bool = false, +}; + +/// `config` with ModelOpt's NVFP4 block after the opening brace: the same geometry, declaring its format. +fn modeloptConfig(buf: []u8) ![]const u8 { + const block = "\"quantization_config\": {\"quant_method\": \"modelopt\", \"quant_algo\": \"NVFP4\", " ++ + "\"config_groups\": {\"group_0\": {\"weights\": {\"num_bits\": 4, \"group_size\": 16, \"type\": \"float\"}}}}, "; + return std.fmt.bufPrint(buf, "{{{s}{s}", .{ block, config[1..] }); +} /// Two shards and their index, a vision tensor among them, and a joint head file the index does not name. fn write(dir: std.Io.Dir, plant: Plant) !void { @@ -131,13 +154,36 @@ fn write(dir: std.Io.Dir, plant: Plant) !void { if (plant.vision_shard) try index.appendSlice(gpa, ",\"model.visual.blocks.0.attn.qkv.weight\": \"model-vision.safetensors\""); try index.appendSlice(gpa, "}}"); try dir.writeFile(io, .{ .sub_path = "model.safetensors.index.json", .data = index.items }); - try dir.writeFile(io, .{ .sub_path = "config.json", .data = config }); + var conf: [1024]u8 = undefined; + const text = if (plant.modelopt) try modeloptConfig(&conf) else config; + try dir.writeFile(io, .{ .sub_path = "config.json", .data = text }); } fn rootOf(tmp: std.testing.TmpDir) ![]u8 { return std.fmt.allocPrint(gpa, ".zig-cache/tmp/{s}", .{tmp.sub_path}); } +/// The full set of tensors `readMtp` needs, so a synthetic head can be read from either source. +fn putMtpHead(f: *File, prefix: []const u8) !void { + const names = [_][]const u8{ + "norm_e.weight", "pre_fc_norm_embedding.weight", "pre_fc_norm_hidden.weight", "norm.weight", + "fc.weight", "layers.0.self_attn.q_proj.weight", "layers.0.self_attn.k_proj.weight", "layers.0.self_attn.v_proj.weight", + "layers.0.self_attn.o_proj.weight", "layers.0.self_attn.q_norm.weight", "layers.0.self_attn.k_norm.weight", "layers.0.input_layernorm.weight", + "layers.0.post_attention_layernorm.weight", "layers.0.mlp.gate_proj.weight", "layers.0.mlp.up_proj.weight", "layers.0.mlp.down_proj.weight", + }; + for (names) |name| try f.put(std.fmt.allocPrint(f.arena.allocator(), "{s}{s}", .{ prefix, name }) catch unreachable, "BF16", &.{64}); +} + +/// An index whose weight map names every tensor in `f` as belonging to `shard`. +fn writeIndex(dir: std.Io.Dir, f: *const File, shard: []const u8) !void { + var index: std.ArrayList(u8) = .empty; + defer index.deinit(gpa); + try index.appendSlice(gpa, "{\"metadata\": {}, \"weight_map\": {"); + for (f.names.items, 0..) |n, i| try index.print(gpa, "{s}\"{s}\": \"{s}\"", .{ if (i > 0) "," else "", n, shard }); + try index.appendSlice(gpa, "}}"); + try dir.writeFile(io, .{ .sub_path = "model.safetensors.index.json", .data = index.items }); +} + fn tensorOf(ck: *const checkpoint.Checkpoint, name: []const u8) ![]const u8 { return (try ck.main.get(name)).bytes; } @@ -223,7 +269,7 @@ test "a bf16 conv weight of rank 2 or 4, or with its 1 elsewhere, is refused" { /// The shards of `root` mapped as a bf16 checkpoint's table, without the checkpoint's checks. fn rawTable(root: []const u8, files: *table.Files) !table.Table { - files.* = try table.Files.indexed(gpa, io, root); + files.* = try table.Files.indexed(gpa, io, root, false); errdefer files.deinit(); return table.Table.open(gpa, io, files.model, "", .{ .bf16 = {} }); } @@ -265,7 +311,7 @@ test "textBytes counts the text tower and the head, not the vision tower or the while (it.next()) |k| if (std.mem.startsWith(u8, k.*, M) or std.mem.eql(u8, k.*, "lm_head.weight")) { want += (try ck.main.get(k.*)).bytes.len; }; - try std.testing.expectEqual(want, try table.textBytes(gpa, io, root)); + try std.testing.expectEqual(want, try table.textBytes(gpa, io, root, 0)); try std.testing.expect(want < (try ck.main.get("model.visual.patch_embed.proj.weight")).bytes.len + want); } @@ -297,11 +343,246 @@ test "a shard the index names only for vision tensors is not opened, even when i try write(tmp.dir, .{ .vision_shard = true }); const root = try rootOf(tmp); defer gpa.free(root); - var files = try table.Files.indexed(gpa, io, root); + var files = try table.Files.indexed(gpa, io, root, false); defer files.deinit(); try std.testing.expectEqual(@as(usize, 2), files.model.len); for (files.model) |p| try std.testing.expect(std.mem.indexOf(u8, p, "vision") == null); var ck = try checkpoint.Checkpoint.open(gpa, io, root); ck.close(); - try std.testing.expect(try table.textBytes(gpa, io, root) > 0); + try std.testing.expect(try table.textBytes(gpa, io, root, 0) > 0); +} + +test "device bytes count a ModelOpt checkpoint's widened tables, not its stored bytes" { + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + var f = File.init(); + defer f.deinit(); + try f.put(M ++ "layers.0.mlp.up_proj.weight", "U8", &.{ 8, 16 }); + try f.put(M ++ "layers.0.mlp.up_proj.weight_scale", "F8_E4M3", &.{ 8, 2 }); + try f.put(M ++ "layers.0.mlp.up_proj.weight_scale_2", "F32", &.{1}); + try f.put(M ++ "embed_tokens.weight", "BF16", &.{ 8, 4 }); + try f.put("model.visual.patch_embed.proj.weight", "BF16", &.{ 8, 8 }); + try f.write(tmp.dir, "model.safetensors"); + var index: std.ArrayList(u8) = .empty; + defer index.deinit(gpa); + try index.appendSlice(gpa, "{\"metadata\": {}, \"weight_map\": {"); + for (f.names.items, 0..) |n, i| try index.print(gpa, "{s}\"{s}\": \"model.safetensors\"", .{ if (i > 0) "," else "", n }); + try index.appendSlice(gpa, "}}"); + try tmp.dir.writeFile(io, .{ .sub_path = "model.safetensors.index.json", .data = index.items }); + const root = try rootOf(tmp); + defer gpa.free(root); + // stored: codes 128, E4M3 table 16, global 4, text 64; the table doubles to 32 on the device, the tower stays out + try std.testing.expectEqual(@as(u64, 228), try table.deviceBytesAt(gpa, io, root)); +} + +test "a bf16 norm the loader widens to f32 costs four bytes a value, not the two it is stored in" { + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + var f = File.init(); + defer f.deinit(); + // one BF16 norm of 64 values: 128 stored, 256 on the device once `projection.float` widens it + try f.put(M ++ "layers.0.input_layernorm.weight", "BF16", &.{64}); + try f.put(M ++ "layers.0.linear_attn.conv1d.weight", "BF16", &.{ 8, 1, 4 }); + try f.put(M ++ "layers.0.linear_attn.A_log", "BF16", &.{2}); + // an embedding and a projection keep their stored width: bf16 reads dense as stored, codes stay codes + try f.put(M ++ "embed_tokens.weight", "BF16", &.{ 8, 4 }); + try f.put(M ++ "layers.0.mlp.up_proj.weight", "U8", &.{ 8, 16 }); + try f.write(tmp.dir, "model.safetensors"); + var index: std.ArrayList(u8) = .empty; + defer index.deinit(gpa); + try index.appendSlice(gpa, "{\"metadata\": {}, \"weight_map\": {"); + for (f.names.items, 0..) |n, i| try index.print(gpa, "{s}\"{s}\": \"model.safetensors\"", .{ if (i > 0) "," else "", n }); + try index.appendSlice(gpa, "}}"); + try tmp.dir.writeFile(io, .{ .sub_path = "model.safetensors.index.json", .data = index.items }); + const root = try rootOf(tmp); + defer gpa.free(root); + // norm 64 values: 128 stored -> 256; conv 32 -> 128; A_log 2 -> 8; embedding 32 -> 64; codes 128 -> 128 + try std.testing.expectEqual(@as(u64, 256 + 128 + 8 + 64 + 128), try table.deviceBytesAt(gpa, io, root)); +} + +test "an indexed MTP shard and an mtp side file both reach Checkpoint.mtp" { + // an index that names the head's own shard, and a head shipped beside it: neither may lose the declared head + const cases = [_]struct { side: bool, shard: bool }{ + .{ .side = false, .shard = true }, + .{ .side = true, .shard = false }, + }; + for (cases) |c| { + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + var body = File.init(); + defer body.deinit(); + try body.put(M ++ "embed_tokens.weight", "BF16", &.{ 16, 64 }); + try body.put(M ++ "norm.weight", "BF16", &.{64}); + try body.write(tmp.dir, "model-00001-of-00002.safetensors"); + var head = File.init(); + defer head.deinit(); + try head.put("mtp.pre_fc_norm_embedding.weight", "BF16", &.{64}); + try head.put("mtp.pre_fc_norm_hidden.weight", "BF16", &.{64}); + try head.put("mtp.norm.weight", "BF16", &.{64}); + try head.put("mtp.fc.weight", "BF16", &.{ 64, 128 }); + try head.put("mtp.layers.0.self_attn.q_proj.weight", "BF16", &.{ 64, 64 }); + try head.put("mtp.layers.0.self_attn.k_proj.weight", "BF16", &.{ 32, 64 }); + try head.put("mtp.layers.0.self_attn.v_proj.weight", "BF16", &.{ 32, 64 }); + try head.put("mtp.layers.0.self_attn.o_proj.weight", "BF16", &.{ 64, 64 }); + try head.put("mtp.layers.0.self_attn.q_norm.weight", "BF16", &.{32}); + try head.put("mtp.layers.0.self_attn.k_norm.weight", "BF16", &.{32}); + try head.put("mtp.layers.0.input_layernorm.weight", "BF16", &.{64}); + try head.put("mtp.layers.0.post_attention_layernorm.weight", "BF16", &.{64}); + try head.put("mtp.layers.0.mlp.gate_proj.weight", "BF16", &.{ 32, 64 }); + try head.put("mtp.layers.0.mlp.up_proj.weight", "BF16", &.{ 32, 64 }); + try head.put("mtp.layers.0.mlp.down_proj.weight", "BF16", &.{ 64, 32 }); + try head.write(tmp.dir, if (c.side) "mtp.safetensors" else "model-00002-of-00002.safetensors"); + var index: std.ArrayList(u8) = .empty; + defer index.deinit(gpa); + try index.appendSlice(gpa, "{\"metadata\": {}, \"weight_map\": {"); + var first = true; + for (body.names.items) |n| { + try index.print(gpa, "{s}\"{s}\": \"model-00001-of-00002.safetensors\"", .{ if (first) "" else ",", n }); + first = false; + } + if (!c.side) for (head.names.items) |n| { + try index.print(gpa, ",\"{s}\": \"model-00002-of-00002.safetensors\"", .{n}); + }; + try index.appendSlice(gpa, "}}"); + try tmp.dir.writeFile(io, .{ .sub_path = "model.safetensors.index.json", .data = index.items }); + var conf: [1024]u8 = undefined; + try tmp.dir.writeFile(io, .{ .sub_path = "config.json", .data = try modeloptConfig(&conf) }); + const root = try rootOf(tmp); + defer gpa.free(root); + var ck = try checkpoint.Checkpoint.open(gpa, io, root); + defer ck.close(); + // before the file selection kept `mtp.*` shards and side files, mtp() saw neither norm and returned null + var m = (try ck.mtp()) orelse return error.TestUnexpectedResult; + defer m.deinit(); + try std.testing.expectEqual(@as(usize, 64), m.fc_e_norm.numel()); + try std.testing.expect(m.gated); + } +} + +test "a ModelOpt qwen3_5_moe checkpoint is refused by name before its shards are read" { + // the same MoE shape config.zig's own test parses, with ModelOpt's quantization block beside it + const text = + \\{"model_type": "qwen3_5_moe", + \\ "hidden_size": 2048, "num_hidden_layers": 4, "num_attention_heads": 16, "num_key_value_heads": 2, + \\ "linear_num_key_heads": 16, "linear_num_value_heads": 32, "linear_key_head_dim": 128, + \\ "linear_value_head_dim": 128, "linear_conv_kernel_dim": 4, "vocab_size": 1000, "rope_theta": 5000000, + \\ "partial_rotary_factor": 0.5, "num_experts": 256, "num_experts_per_tok": 8, + \\ "moe_intermediate_size": 512, "shared_expert_intermediate_size": 512, "eos_token_id": 1, + \\ "quantization_config": {"quant_method": "modelopt", "quant_algo": "NVFP4", + \\ "config_groups": {"group_0": {"weights": {"num_bits": 4, "group_size": 16, "type": "float"}}}}} + ; + var cfg = try qcfg.Config.parse(gpa, text, null); + defer cfg.deinit(); + try std.testing.expect(cfg.modelopt and cfg.spec.experts > 0); + // before this refusal the same checkpoint opened and its stack reached experts.routed, which is not read + const why = checkpoint.modelOptExpertsWhy(&cfg) orelse return error.TestUnexpectedResult; + try std.testing.expect(std.mem.indexOf(u8, why, "routed experts") != null); +} + +test "a ModelOpt checkpoint's own bf16 layers read dense, not rocBLAS BF16" { + // the same BF16 tensor: an unquantized checkpoint keeps it on rocBLAS, a ModelOpt one on the dense kernels + const cases = [_]struct { modelopt: bool, want: std.meta.Tag(host.Projection) }{ + .{ .modelopt = false, .want = .bf16 }, + .{ .modelopt = true, .want = .dense }, + }; + for (cases) |c| { + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + try write(tmp.dir, .{ .modelopt = c.modelopt }); + const root = try rootOf(tmp); + defer gpa.free(root); + var ck = try checkpoint.Checkpoint.open(gpa, io, root); + defer ck.close(); + // the flag is the config's: an NVFP4 block in config.json, read by open(), not set on the table by the test + try std.testing.expectEqual(c.modelopt, ck.main.modelopt); + var l1 = try ck.layer(1); + defer l1.deinit(); + try std.testing.expectEqual(c.want, std.meta.activeTag(l1.body.full.mlp.dense.gate)); + } +} + +test "an FP8 weight holding an E4M3 nan code is refused; the same FP8 weight reads when it is finite" { + const nan = [_]struct { plant: bool, want_nan: bool }{ + .{ .plant = false, .want_nan = false }, + .{ .plant = true, .want_nan = true }, + }; + for (nan) |c| { + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + var f = File.init(); + defer f.deinit(); + f.fp8_nan = c.plant; + try f.put("lm_head.weight", "F8_E4M3", &.{ 16, 64 }); + try f.put("lm_head.weight_scale", "F32", &.{1}); + try f.write(tmp.dir, "model.safetensors"); + const root = try rootOf(tmp); + defer gpa.free(root); + var files: table.Files = undefined; + var t = try rawTable(root, &files); + defer files.deinit(); + defer t.close(io); + var arena: std.heap.ArenaAllocator = .init(gpa); + defer arena.deinit(); + var why: modelopt.Why = .{}; + const got = modelopt.readWhy(arena.allocator(), &t, "lm_head", .fp8, &why); + if (c.want_nan) { + try std.testing.expectError(error.UnexpectedTensor, got); + // the refusal names the tensor, not a half-filled buffer + try std.testing.expectEqualStrings("lm_head.weight: an FP8 weight holds an E4M3 nan code", why.text()); + } else { + try std.testing.expectEqual(std.meta.Tag(host.Projection).fp8, std.meta.activeTag(try got)); + try std.testing.expectEqual(@as(usize, 0), why.len); + } + } +} + +test "a fused FP8 MTP fc splits along K: contiguous code halves, every row kept, one F32 scale shared" { + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + var f = File.init(); + defer f.deinit(); + // a Qwen-shaped head: the pre-FC norms beside the fused FC the loader always cuts in two + try f.put("mtp.pre_fc_norm_embedding.weight", "BF16", &.{64}); + try f.put("mtp.pre_fc_norm_hidden.weight", "BF16", &.{64}); + try f.put("mtp.fc.weight", "F8_E4M3", &.{ 64, 128 }); + try f.put("mtp.fc.weight_scale", "F32", &.{1}); + try f.write(tmp.dir, "model.safetensors"); + const root = try rootOf(tmp); + defer gpa.free(root); + var files = try table.Files.list(gpa, io, root); + defer files.deinit(); + var t = try table.Table.open(gpa, io, files.model, "", .{ .bf16 = {} }); + defer t.close(io); + var arena: std.heap.ArenaAllocator = .init(gpa); + defer arena.deinit(); + const a = arena.allocator(); + // the pre-FC norms read as fp32 floats, as the head's own read does + for ([_][]const u8{ "mtp.pre_fc_norm_embedding.weight", "mtp.pre_fc_norm_hidden.weight" }) |name| { + const norm = try projection.float(a, &t, name); + try std.testing.expectEqual(table.DType.f32, norm.dtype); + try std.testing.expectEqual(@as(usize, 64), norm.numel()); + } + const fused = try projection.projection(a, &t, "mtp.fc"); + try std.testing.expectEqual(std.meta.Tag(host.Projection).fp8, std.meta.activeTag(fused)); + const halves = try projection.halves(a, fused); + const first = halves[0].fp8; + const second = halves[1].fp8; + const stored = try t.get("mtp.fc.weight"); + const codes = stored.bytes; + const scale = (try t.get("mtp.fc.weight_scale")).bytes; + // shapes: each half is [64, 64], no row dropped + try std.testing.expectEqual(@as(usize, 64), first.weight.shape[0]); + try std.testing.expectEqual(@as(usize, 64), first.weight.shape[1]); + try std.testing.expectEqual(@as(usize, 64), second.weight.shape[0]); + try std.testing.expectEqual(@as(usize, 64), second.weight.shape[1]); + // code bytes: contiguous halves of each row, in row order + for ([_]usize{ 0, 63 }) |r| { + try std.testing.expectEqualSlices(u8, codes[r * 128 ..][0..64], first.weight.bytes[r * 64 ..][0..64]); + try std.testing.expectEqualSlices(u8, codes[r * 128 + 64 ..][0..64], second.weight.bytes[r * 64 ..][0..64]); + } + // the projection's one F32 scale, the same slice on both halves + try std.testing.expectEqual(@as(usize, 1), first.scale.len); + try std.testing.expect(fused.fp8.scale.ptr == first.scale.ptr and fused.fp8.scale.ptr == second.scale.ptr); + try std.testing.expectEqual(convert.load(.f32, scale, 0), first.scale[0]); + try std.testing.expectEqual(convert.load(.f32, scale, 0), second.scale[0]); } diff --git a/zig/src/families/qwen3_5/weights/config.zig b/zig/src/families/qwen3_5/weights/config.zig index 0d7f666611e..9b6383cf93b 100644 --- a/zig/src/families/qwen3_5/weights/config.zig +++ b/zig/src/families/qwen3_5/weights/config.zig @@ -2,6 +2,7 @@ const std = @import("std"); const quant = @import("core").quant; +const modelopt_core = @import("core").modelopt; const shared = @import("../config.zig"); pub const Error = shared.Error || error{UnsupportedQuantization}; @@ -11,10 +12,36 @@ pub const Width = quant.mlx.Width; pub const Spec = shared.Spec; +/// Whether the checkpoint declares ModelOpt's own formats, at the root's `quantization_config` or in `q`. +fn isModelOpt(root: std.json.ObjectMap, q: std.json.ObjectMap) bool { + if (root.get("quantization_config")) |qc| if (qc == .object) { + if (declaresModelOpt(qc.object)) return true; + }; + return declaresModelOpt(q); +} + +/// The checks themselves: `quant_method`, `producer`, `quant_algo`, and the per-module table. +fn declaresModelOpt(q: std.json.ObjectMap) bool { + if (q.get("quant_method")) |m| if (m == .string and std.mem.eql(u8, m.string, "modelopt")) return true; + if (q.get("producer")) |p| if (p == .object) if (p.object.get("name")) |n| if (n == .string and std.mem.eql(u8, n.string, "modelopt")) return true; + if (q.get("quant_algo")) |a| if (a == .string) { + if (std.mem.eql(u8, a.string, "NVFP4") or std.mem.eql(u8, a.string, "MIXED_PRECISION")) return true; + }; + if (q.get("quantized_layers")) |l| if (l == .object) { + var it = l.object.iterator(); + while (it.next()) |kv| if (kv.value_ptr.* == .object) if (kv.value_ptr.object.get("quant_algo")) |a| if (a == .string) { + if (std.mem.eql(u8, a.string, "NVFP4") or std.mem.eql(u8, a.string, "FP8")) return true; + }; + }; + return false; +} + pub const Config = struct { arena: std.heap.ArenaAllocator, spec: Spec, quant: quant.Config, + /// ModelOpt's weight-only format, NVFP4 as stored: a chat checkpoint, not a decision backbone. + modelopt: bool = false, /// `tie_word_embeddings`: the output head is the embedding. tied: bool, /// The end ids of config.json and generation_config.json. @@ -25,6 +52,25 @@ pub const Config = struct { c.* = undefined; } + /// core/modelopt.zig's admission of the checkpoint's recipes: this backend reads NVFP4 and FP8 alone. + fn admitted(gpa: std.mem.Allocator, bytes: []const u8) Error!modelopt_core.Recipes { + var why: modelopt_core.Why = .{}; + var r = modelopt_core.admitRecipes(gpa, bytes, &why) catch { + std.log.err("{s}", .{why.text()}); + return error.UnsupportedQuantization; + }; + errdefer r.deinit(); + var it = r.modules.iterator(); + while (it.next()) |e| switch (e.value_ptr.*) { + .nvfp4, .fp8 => {}, + else => { + std.log.err("{s}: ModelOpt {s} is not a recipe this backend reads", .{ e.key_ptr.*, @tagName(e.value_ptr.*) }); + return error.UnsupportedQuantization; + }, + }; + return r; + } + /// The config of the checkpoint directory `dir`. pub fn read(gpa: std.mem.Allocator, io: std.Io, dir: []const u8) !Config { const path = try std.fs.path.join(gpa, &.{ dir, "config.json" }); @@ -49,15 +95,22 @@ pub const Config = struct { const doc = try shared.declared(a, bytes); const tower = try shared.textTower(doc); const sources: quant.Sources = .{ .root = doc, .quantization = try shared.pickObject(doc, tower, "quantization") }; - // the family's own order: an unquantized BF16 checkpoint first, then the shared formats - const table: quant.Config = if (try quant.bf16.detect(a, sources)) |b| .{ .bf16 = b } else try quant.detect(a, sources); + // the family's own order: ModelOpt's NVFP4 as stored, an unquantized BF16 checkpoint, then the shared formats + const modelopt = isModelOpt(doc, sources.quantization); + if (modelopt) { + var r = try admitted(gpa, bytes); + r.deinit(); + } + const table: quant.Config = if (modelopt) + .{ .bf16 = {} } + else if (try quant.bf16.detect(a, sources)) |b| .{ .bf16 = b } else try quant.detect(a, sources); const width: Width = if (table == .bf16) .{ .bits = 16, .group = 0 } else try table.width(""); const spec = try shared.geometry(tower, width.bits, width.group); const gen = if (generation) |g| (try std.json.parseFromSliceLeaky(std.json.Value, a, g, .{})) else null; if (gen) |g| if (g != .object) return error.InvalidConfig; const ids = try a.create([shared.checks.max_eos]u32); const eos = try shared.checks.eos(ids, doc, tower, if (gen) |g| g.object else null, spec.vocab); - return .{ .arena = arena, .spec = spec, .quant = table, .tied = try shared.isTied(doc, tower), .eos = eos }; + return .{ .arena = arena, .spec = spec, .quant = table, .modelopt = modelopt, .tied = try shared.isTied(doc, tower), .eos = eos }; } }; @@ -117,3 +170,16 @@ test "a config with no quantization is the bf16 format: 16 bits, no groups, no w defer a.free(named); try std.testing.expectError(error.UnsupportedQuantization, Config.parse(a, named, null)); } + +test "a single-format ModelOpt FP8 config parses as a ModelOpt checkpoint" { + const a = std.testing.allocator; + const fp8 = try std.fmt.allocPrint(a, "{{{s}{s}", .{ + "\"quantization_config\": {\"quant_method\": \"modelopt\", \"quant_algo\": \"FP8\"}, ", + sample[1..], + }); + defer a.free(fp8); + var c = try Config.parse(a, fp8, null); + defer c.deinit(); + try std.testing.expect(c.modelopt); + try std.testing.expectEqual(quant.Format.bf16, std.meta.activeTag(c.quant)); +} diff --git a/zig/src/families/qwen3_5/weights/host.zig b/zig/src/families/qwen3_5/weights/host.zig index f2d2f8dee96..79ca38a33a1 100644 --- a/zig/src/families/qwen3_5/weights/host.zig +++ b/zig/src/families/qwen3_5/weights/host.zig @@ -6,8 +6,111 @@ const table = @import("table.zig"); pub const Tensor = table.Tensor; -/// A projection as its format read it from the checkpoint. -pub const Projection = quant.Host; +/// A projection as its format read it from the checkpoint: the shared formats, or ModelOpt's NVFP4. +pub const Projection = union(enum) { + mlx: quant.mlx.Host, + dense: quant.dense.Host, + bf16: quant.bf16.Host, + nvfp4: quant.nvfp4.Host, + fp8: StoredFp8, + + /// Output rows N. + pub fn rows(p: Projection) usize { + return switch (p) { + .mlx => |h| quant.mlx.rows(h), + .dense => |h| quant.dense.rows(h), + .bf16 => |h| quant.bf16.rows(h), + .nvfp4 => |h| quant.nvfp4.rows(h), + .fp8 => |h| h.rows(), + }; + } + + /// The host bytes the projection holds. + pub fn bytes(p: Projection) usize { + return switch (p) { + .mlx => |h| quant.mlx.bytes(h), + .dense => |h| quant.dense.bytes(h), + .bf16 => |h| quant.bf16.bytes(h), + .nvfp4 => |h| quant.nvfp4.bytes(h), + .fp8 => |h| h.bytes(), + }; + } +}; + +/// The shared formats' projection as this family reads it (a ModelOpt checkpoint goes through `modelopt.zig`). +pub fn read(a: std.mem.Allocator, t: anytype, key: []const u8) !Projection { + return switch (try quant.read(a, t, key)) { + .mlx => |x| .{ .mlx = x }, + .dense => |x| .{ .dense = x }, + .bf16 => |x| .{ .bf16 = x }, + }; +} + +/// A fused projection as its two halves along K. +pub fn halves(a: std.mem.Allocator, p: Projection) ![2]Projection { + return switch (p) { + .mlx => |x| pair(.mlx, try quant.mlx.halves(a, x)), + .dense => |x| pair(.dense, try quant.dense.halves(a, x)), + .bf16 => |x| pair(.bf16, try quant.bf16.halves(a, x)), + .nvfp4 => |x| pair(.nvfp4, try quant.nvfp4.halves(a, x)), + .fp8 => |x| pair(.fp8, try fp8Halves(a, x)), + }; +} + +/// A fused FP8 [N, K] projection's two halves along K: contiguous code halves, the projection's one scale shared. +fn fp8Halves(a: std.mem.Allocator, p: StoredFp8) ![2]StoredFp8 { + const k = p.weight.shape[1]; + if (k % 2 != 0) return error.UnevenSplit; + return .{ + .{ .weight = try quant.slice.takeCols(a, p.weight, 0, k / 2), .scale = p.scale }, + .{ .weight = try quant.slice.takeCols(a, p.weight, k / 2, k), .scale = p.scale }, + }; +} + +/// Output rows `spans`: a column-split projection's share on one rank. +pub fn sliceRows(a: std.mem.Allocator, p: Projection, spans: []const quant.Span) !Projection { + return switch (p) { + .mlx => |x| one(.mlx, try quant.mlx.sliceRows(a, x, spans)), + .dense => |x| one(.dense, try quant.dense.sliceRows(a, x, spans)), + .bf16 => |x| one(.bf16, try quant.bf16.sliceRows(a, x, spans)), + .nvfp4 => |x| one(.nvfp4, try quant.nvfp4.sliceRows(a, x, spans)), + .fp8 => error.UnevenSplit, + }; +} + +/// One rank's input groups of a row-split projection. +pub fn sliceCols(a: std.mem.Allocator, p: Projection, r: quant.Rank, what: []const u8) !Projection { + return switch (p) { + .mlx => |x| one(.mlx, try quant.mlx.sliceCols(a, x, r, what)), + .dense => |x| one(.dense, try quant.dense.sliceCols(a, x, r, what)), + .bf16 => |x| one(.bf16, try quant.bf16.sliceCols(a, x, r, what)), + .nvfp4 => |x| one(.nvfp4, try quant.nvfp4.sliceCols(a, x, r, what)), + .fp8 => error.UnevenSplit, + }; +} + +fn one(comptime tag: std.meta.Tag(Projection), v: anytype) Projection { + return @unionInit(Projection, @tagName(tag), v); +} + +fn pair(comptime tag: std.meta.Tag(Projection), v: anytype) [2]Projection { + return .{ one(tag, v[0]), one(tag, v[1]) }; +} + +/// A ModelOpt FP8 projection as the checkpoint stores it: E4M3 codes one a byte and one f32 scale. +pub const StoredFp8 = struct { + weight: Tensor, + /// The projection's one scale. + scale: []const f32, + + pub fn rows(p: StoredFp8) usize { + return p.weight.shape[0]; + } + + pub fn bytes(p: StoredFp8) usize { + return p.weight.bytes.len + p.scale.len * 4; + } +}; /// A layer's E + 1 experts, shared last, and its router rows (core/quant/experts.zig). pub const Experts = quant.experts.Experts; diff --git a/zig/src/families/qwen3_5/weights/modelopt.zig b/zig/src/families/qwen3_5/weights/modelopt.zig new file mode 100644 index 00000000000..c902fd15588 --- /dev/null +++ b/zig/src/families/qwen3_5/weights/modelopt.zig @@ -0,0 +1,76 @@ +//! ModelOpt's weight-only formats, NVFP4 and FP8, kept as stored with a product kernel decoding each in flight. + +const std = @import("std"); +const core = @import("core"); +const quant = core.quant; +const bf16_round = core.bf16_round; +const table = @import("table.zig"); +const host = @import("host.zig"); + +const convert = quant.convert; +const Tensor = table.Tensor; +const Allocator = std.mem.Allocator; + +/// Inputs sharing one NVFP4 scale, as ModelOpt writes it. +pub const group = quant.nvfp4.group; + +/// Why the reader refused a tensor, kept for the caller's log line (tests read it instead). +pub const Why = @import("core").modelopt.Why; + +/// The ModelOpt algorithms this reader takes. +pub const Algo = enum { nvfp4, fp8 }; + +/// `key`'s stored algorithm, by the tensors beside it; null when they are not ModelOpt's. +pub fn algo(t: *const table.Table, key: []const u8) ?Algo { + var w: [320]u8 = undefined; + var s2: [320]u8 = undefined; + var s: [320]u8 = undefined; + if (!t.has(name(&w, key, ".weight") orelse return null)) return null; + if (t.has(name(&s2, key, ".weight_scale_2") orelse return null)) return .nvfp4; + if (t.has(name(&s, key, ".weight_scale") orelse return null)) return .fp8; + return null; +} + +fn name(buf: []u8, key: []const u8, suffix: []const u8) ?[]const u8 { + return std.fmt.bufPrint(buf, "{s}{s}", .{ key, suffix }) catch null; +} + +/// `key`'s projection: ModelOpt's NVFP4 and FP8 stay as stored, their kernels decoding in flight. +pub fn read(a: Allocator, t: *const table.Table, key: []const u8, what: Algo) !host.Projection { + var why: Why = .{}; + return readWhy(a, t, key, what, &why) catch |e| { + if (why.len > 0) std.log.err("{s}", .{why.text()}); + return e; + }; +} + +/// `read`, the refusal kept in `why` instead of the log (tests read it). +pub fn readWhy(a: Allocator, t: *const table.Table, key: []const u8, what: Algo, why: *Why) !host.Projection { + return switch (what) { + .nvfp4 => .{ .nvfp4 = try quant.nvfp4.read(a, t, key) }, + .fp8 => .{ .fp8 = try fp8(a, t, key, why) }, + }; +} + +fn fp8(a: Allocator, t: *const table.Table, key: []const u8, why: *Why) !host.StoredFp8 { + var b: [2][320]u8 = undefined; + const wname = name(&b[0], key, ".weight") orelse return error.MissingTensor; + const sname = name(&b[1], key, ".weight_scale") orelse return error.MissingTensor; + const w = try t.get(wname); + const s = try t.get(sname); + if (w.dtype != .f8_e4m3 or w.rank != 2) return refuse(why, wname, "an FP8 weight is E4M3 [N, K]"); + if (s.dtype != .f32) return refuse(why, sname, "FP8's weight scale is F32"); + if (s.numel() != 1) return refuse(why, sname, "FP8's weight scale is one number a projection, as ModelOpt writes it"); + const one = convert.load(.f32, s.bytes, 0); + if (!std.math.isFinite(one) or one == 0) return refuse(why, sname, "FP8's weight scale is zero, infinite or nan"); + for (w.bytes) |byte| if (byte & 0x7f == 0x7f) return refuse(why, wname, "an FP8 weight holds an E4M3 nan code"); + // the codes stay as stored; the product kernel decodes them and applies this scale once to its f32 sum + const scale = try a.alloc(f32, 1); + scale[0] = one; + return .{ .weight = w, .scale = scale }; +} + +fn refuse(why: *Why, key: []const u8, what: []const u8) error{UnexpectedTensor} { + why.set("{s}: {s}", .{ key, what }); + return error.UnexpectedTensor; +} diff --git a/zig/src/families/qwen3_5/weights/mtp_source_test.zig b/zig/src/families/qwen3_5/weights/mtp_source_test.zig new file mode 100644 index 00000000000..b022f72fe93 --- /dev/null +++ b/zig/src/families/qwen3_5/weights/mtp_source_test.zig @@ -0,0 +1,375 @@ +//! Host tests of MTP source selection: presence, classification and byte accounting. + +const std = @import("std"); +const checkpoint = @import("checkpoint.zig"); +const table = @import("table.zig"); + +const io = std.testing.io; +const gpa = std.testing.allocator; + +const M = "model.language_model."; + +const config = + \\{"model_type": "qwen3_5", "tie_word_embeddings": false, + \\ "text_config": {"hidden_size": 64, "intermediate_size": 32, "num_hidden_layers": 2, + \\ "num_attention_heads": 2, "num_key_value_heads": 1, "head_dim": 32, "linear_num_key_heads": 1, + \\ "linear_num_value_heads": 2, "linear_key_head_dim": 32, "linear_value_head_dim": 16, + \\ "linear_conv_kernel_dim": 4, "vocab_size": 16, "full_attention_interval": 2, "mtp_num_hidden_layers": 0, + \\ "layer_types": ["linear_attention", "full_attention"], "eos_token_id": 1}} +; + +const File = struct { + arena: std.heap.ArenaAllocator, + names: std.ArrayList([]const u8) = .empty, + header: std.ArrayList(u8) = .empty, + data: std.ArrayList(u8) = .empty, + + fn init() File { + return .{ .arena = .init(gpa) }; + } + + fn deinit(f: *File) void { + f.arena.deinit(); + } + + fn put(f: *File, name: []const u8, dtype: []const u8, shape: []const usize) !void { + const a = f.arena.allocator(); + var n: usize = 1; + for (shape) |d| n *= d; + const start = f.data.items.len; + // 0x3e80 is BF16's 0.25: finite and shape-correct for the synthetic heads + for (0..n) |_| try f.data.appendSlice(a, &std.mem.toBytes(@as(u16, 0x3e80))); + if (f.names.items.len > 0) try f.header.append(a, ','); + try f.header.print(a, "\"{s}\":{{\"dtype\":\"{s}\",\"shape\":[", .{ name, dtype }); + for (shape, 0..) |d, j| { + if (j > 0) try f.header.append(a, ','); + try f.header.print(a, "{d}", .{d}); + } + try f.header.print(a, "],\"data_offsets\":[{d},{d}]}}", .{ start, f.data.items.len }); + try f.names.append(a, try a.dupe(u8, name)); + } + + fn write(f: *File, dir: std.Io.Dir, path: []const u8) !void { + const a = f.arena.allocator(); + var out: std.ArrayList(u8) = .empty; + try out.appendSlice(a, &std.mem.toBytes(std.mem.nativeToLittle(u64, f.header.items.len + 2))); + try out.append(a, '{'); + try out.appendSlice(a, f.header.items); + try out.append(a, '}'); + try out.appendSlice(a, f.data.items); + try dir.writeFile(io, .{ .sub_path = path, .data = out.items }); + } +}; + +fn modeloptConfig(buf: []u8) ![]const u8 { + const block = "\"quantization_config\": {\"quant_method\": \"modelopt\", \"quant_algo\": \"NVFP4\", " ++ + "\"config_groups\": {\"group_0\": {\"weights\": {\"num_bits\": 4, \"group_size\": 16, \"type\": \"float\"}}}}, "; + return std.fmt.bufPrint(buf, "{{{s}{s}", .{ block, config[1..] }); +} + +fn rootOf(tmp: std.testing.TmpDir) ![]u8 { + return std.fmt.allocPrint(gpa, ".zig-cache/tmp/{s}", .{tmp.sub_path}); +} + +/// The tensors `readMtp` needs for one source, so a synthetic head has no unused leftovers. +fn putMtpHead(f: *File, prefix: []const u8, gated: bool) !void { + const flash = [_][]const u8{ + "norm_e.weight", "norm_h.weight", "q_norm.weight", "k_norm.weight", "final_norm.weight", + "fc_e.weight", "fc_h.weight", "q_proj.weight", "k_proj.weight", "v_proj.weight", + "o_proj.weight", + }; + const gated_names = [_][]const u8{ + "pre_fc_norm_embedding.weight", "pre_fc_norm_hidden.weight", "norm.weight", + "layers.0.self_attn.q_norm.weight", "layers.0.self_attn.k_norm.weight", "layers.0.input_layernorm.weight", + "layers.0.post_attention_layernorm.weight", "fc.weight", "layers.0.self_attn.q_proj.weight", + "layers.0.self_attn.k_proj.weight", "layers.0.self_attn.v_proj.weight", "layers.0.self_attn.o_proj.weight", + "layers.0.mlp.gate_proj.weight", "layers.0.mlp.up_proj.weight", "layers.0.mlp.down_proj.weight", + }; + const chosen: []const []const u8 = if (gated) &gated_names else &flash; + for (chosen) |name| { + const rank2 = std.mem.indexOf(u8, name, "proj") != null or std.mem.startsWith(u8, name, "fc"); + const shape: []const usize = if (rank2) &.{ 64, 64 } else &.{64}; + try f.put(std.fmt.allocPrint(f.arena.allocator(), "{s}{s}", .{ prefix, name }) catch unreachable, "BF16", shape); + } +} + +/// An index whose weight map names every tensor in `f` as belonging to `shard`. +fn writeIndex(dir: std.Io.Dir, f: *const File, shard: []const u8) !void { + var index: std.ArrayList(u8) = .empty; + defer index.deinit(gpa); + try index.appendSlice(gpa, "{\"metadata\": {}, \"weight_map\": {"); + for (f.names.items, 0..) |n, i| { + if (i > 0) try index.append(gpa, ','); + try index.print(gpa, "\"{s}\": \"{s}\"", .{ n, shard }); + } + try index.appendSlice(gpa, "}}"); + try dir.writeFile(io, .{ .sub_path = "model.safetensors.index.json", .data = index.items }); +} + +/// The source preflight settles on, exactly as `Checkpoint.open` does. +fn preflightSource(root: []const u8) !?table.MtpSource { + var files = try table.Files.indexed(gpa, io, root, true); + defer files.deinit(); + return files.mtpSource(gpa, io); +} + +/// The same selection reached through the other entry point, for a ModelOpt checkpoint. +fn preflightDeviceBytes(root: []const u8) !u64 { + var files = try table.Files.indexed(gpa, io, root, true); + defer files.deinit(); + return table.deviceBytes(gpa, io, root, try files.mtpSource(gpa, io)); +} + +fn expectSameSource(want: ?table.MtpSource, got: ?table.MtpSource) !void { + if (want == null or got == null) return std.testing.expect(want == null and got == null); + try std.testing.expectEqual(want.?.side, got.?.side); + try std.testing.expectEqual(want.?.main, got.?.main); + try std.testing.expectEqual(want.?.paths.len, got.?.paths.len); +} + +test "MTP source: device bytes count the selected head once with both copies present" { + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + var body = File.init(); + defer body.deinit(); + try body.put(M ++ "embed_tokens.weight", "BF16", &.{ 8, 4 }); + try body.write(tmp.dir, "model.safetensors"); + var indexed = File.init(); + defer indexed.deinit(); + try putMtpHead(&indexed, "mtp.", false); + try indexed.write(tmp.dir, "model-mtp.safetensors"); + try writeIndex(tmp.dir, &body, "model.safetensors"); + var conf: [1024]u8 = undefined; + try tmp.dir.writeFile(io, .{ .sub_path = "config.json", .data = try modeloptConfig(&conf) }); + const root = try rootOf(tmp); + defer gpa.free(root); + const head_only = try table.deviceBytesAt(gpa, io, root); + var side = File.init(); + defer side.deinit(); + try putMtpHead(&side, "language_model.mtp.", false); + try side.write(tmp.dir, "mtp.safetensors"); + // the same head from a side file must not add a second copy's bytes: 64 embed + 50432 flash head + const both = try table.deviceBytesAt(gpa, io, root); + try std.testing.expectEqual(@as(u64, 64 + 50432), both); + try std.testing.expectEqual(head_only, both); + try std.testing.expect((try preflightSource(root)).?.side); +} + +test "MTP source: an embedded head loads when the config declares zero layers" { + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + var body = File.init(); + defer body.deinit(); + try body.put(M ++ "embed_tokens.weight", "BF16", &.{ 16, 64 }); + try putMtpHead(&body, "mtp.", true); + try body.write(tmp.dir, "model.safetensors"); + try writeIndex(tmp.dir, &body, "model.safetensors"); + // a zero-declaration config must not hide a present embedded head + try tmp.dir.writeFile(io, .{ .sub_path = "config.json", .data = config }); + const root = try rootOf(tmp); + defer gpa.free(root); + var ck = try checkpoint.Checkpoint.open(gpa, io, root); + defer ck.close(); + try std.testing.expectEqual(@as(usize, 0), ck.spec().mtp_layers); + // the loader and preflight reach the same source, and it is the main table + try expectSameSource(try preflightSource(root), ck.mtp_source); + try std.testing.expect(ck.mtp_source.?.main); + var m = (try ck.mtp()) orelse return error.TestUnexpectedResult; + defer m.deinit(); + try std.testing.expect(m.owned == null); + // a plain bf16 checkpoint is counted by `textBytes`: the tower and the head it reads, 2048 + 66432 + try std.testing.expectEqual(@as(u64, 2048 + 66432), try table.textBytes(gpa, io, root, 0)); + // a config that declares MTP layers makes the loader refuse this head, so its bytes stay out + try std.testing.expectEqual(@as(u64, 2048), try table.textBytes(gpa, io, root, 1)); +} + +test "MTP source: an indexed model-mtp.safetensors head loads and is accounted for" { + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + var body = File.init(); + defer body.deinit(); + try body.put(M ++ "embed_tokens.weight", "BF16", &.{ 16, 64 }); + try body.write(tmp.dir, "model.safetensors"); + var head = File.init(); + defer head.deinit(); + try putMtpHead(&head, "mtp.", false); + try head.write(tmp.dir, "model-mtp.safetensors"); + var index: std.ArrayList(u8) = .empty; + defer index.deinit(gpa); + try index.appendSlice(gpa, "{\"metadata\": {}, \"weight_map\": {"); + try index.print(gpa, "\"{s}\": \"model.safetensors\"", .{body.names.items[0]}); + for (head.names.items) |n| try index.print(gpa, ",\"{s}\": \"model-mtp.safetensors\"", .{n}); + try index.appendSlice(gpa, "}}"); + try tmp.dir.writeFile(io, .{ .sub_path = "model.safetensors.index.json", .data = index.items }); + var conf: [1024]u8 = undefined; + try tmp.dir.writeFile(io, .{ .sub_path = "config.json", .data = try modeloptConfig(&conf) }); + const root = try rootOf(tmp); + defer gpa.free(root); + var files = try table.Files.indexed(gpa, io, root, true); + defer files.deinit(); + // the backbone shard stays in the model set; the MTP-named one goes to the side set + try std.testing.expectEqual(@as(usize, 1), files.model.len); + try std.testing.expectEqual(@as(usize, 1), files.side.len); + try std.testing.expect(try table.deviceBytesAt(gpa, io, root) > 0); + var ck = try checkpoint.Checkpoint.open(gpa, io, root); + defer ck.close(); + var m = (try ck.mtp()) orelse return error.TestUnexpectedResult; + defer m.deinit(); + try std.testing.expect(m.owned != null); +} + +test "MTP source: a combined indexed and side checkpoint observes which source won" { + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + var body = File.init(); + defer body.deinit(); + try body.put(M ++ "embed_tokens.weight", "BF16", &.{ 16, 64 }); + try body.write(tmp.dir, "model.safetensors"); + var indexed = File.init(); + defer indexed.deinit(); + try putMtpHead(&indexed, "mtp.", false); + try indexed.write(tmp.dir, "model-mtp.safetensors"); + var side = File.init(); + defer side.deinit(); + try putMtpHead(&side, "language_model.mtp.", false); + try side.write(tmp.dir, "mtp.safetensors"); + try writeIndex(tmp.dir, &body, "model.safetensors"); + var conf: [1024]u8 = undefined; + try tmp.dir.writeFile(io, .{ .sub_path = "config.json", .data = try modeloptConfig(&conf) }); + const root = try rootOf(tmp); + defer gpa.free(root); + var ck = try checkpoint.Checkpoint.open(gpa, io, root); + defer ck.close(); + var m = (try ck.mtp()) orelse return error.TestUnexpectedResult; + defer m.deinit(); + // side precedence: the side table is retained, not the main table's indexed copy + try std.testing.expect(m.owned != null); +} + +test "MTP source: an ordinary-shard head and a side file load and count from the side" { + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + var body = File.init(); + defer body.deinit(); + try body.put(M ++ "embed_tokens.weight", "BF16", &.{ 16, 64 }); + try putMtpHead(&body, "mtp.", true); + try body.write(tmp.dir, "model.safetensors"); + // the side head uses the gated branch, so counting it instead of the flash copy changes the total + var side = File.init(); + defer side.deinit(); + try putMtpHead(&side, "language_model.mtp.", true); + try side.write(tmp.dir, "mtp.safetensors"); + try writeIndex(tmp.dir, &body, "model.safetensors"); + var conf: [1024]u8 = undefined; + try tmp.dir.writeFile(io, .{ .sub_path = "config.json", .data = try modeloptConfig(&conf) }); + const root = try rootOf(tmp); + defer gpa.free(root); + var files = try table.Files.indexed(gpa, io, root, true); + defer files.deinit(); + try std.testing.expectEqual(@as(usize, 1), files.side.len); + var ck = try checkpoint.Checkpoint.open(gpa, io, root); + defer ck.close(); + // the side file wins, and both the loader and preflight observe that same source + const source = ck.mtp_source orelse return error.TestUnexpectedResult; + try std.testing.expect(source.side); + try std.testing.expect(!source.main); + try expectSameSource(try preflightSource(root), ck.mtp_source); + var m = (try ck.mtp()) orelse return error.TestUnexpectedResult; + defer m.deinit(); + try std.testing.expect(m.owned != null); + // the gated head is what the side file holds: 2048 embed + 67328 gated head, the indexed copy left out + try std.testing.expectEqual(@as(u64, 2048 + 67328), try preflightDeviceBytes(root)); + try std.testing.expectEqual(@as(u64, 2048 + 67328), try table.deviceBytesAt(gpa, io, root)); + // a flash side head in the same layout adds up to a different, exact total + try std.testing.expectEqual(@as(u64, 2048 + 50432), try fixtureBytes(false)); +} + +/// Device bytes of the same checkpoint with a flash instead of gated side head, in its own directory. +fn fixtureBytes(gated: bool) !u64 { + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + var body = File.init(); + defer body.deinit(); + try body.put(M ++ "embed_tokens.weight", "BF16", &.{ 16, 64 }); + try putMtpHead(&body, "mtp.", true); + try body.write(tmp.dir, "model.safetensors"); + var side = File.init(); + defer side.deinit(); + try putMtpHead(&side, "language_model.mtp.", gated); + try side.write(tmp.dir, "mtp.safetensors"); + try writeIndex(tmp.dir, &body, "model.safetensors"); + var conf: [1024]u8 = undefined; + try tmp.dir.writeFile(io, .{ .sub_path = "config.json", .data = try modeloptConfig(&conf) }); + const root = try rootOf(tmp); + defer gpa.free(root); + return table.deviceBytesAt(gpa, io, root); +} + +test "MTP source: an embedded language_model.mtp head loads with no side file" { + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + var body = File.init(); + defer body.deinit(); + try body.put(M ++ "embed_tokens.weight", "BF16", &.{ 16, 64 }); + try putMtpHead(&body, "language_model.mtp.", false); + try body.write(tmp.dir, "model.safetensors"); + try writeIndex(tmp.dir, &body, "model.safetensors"); + try tmp.dir.writeFile(io, .{ .sub_path = "config.json", .data = config }); + const root = try rootOf(tmp); + defer gpa.free(root); + var files = try table.Files.indexed(gpa, io, root, true); + defer files.deinit(); + try std.testing.expectEqual(@as(usize, 0), files.side.len); + var ck = try checkpoint.Checkpoint.open(gpa, io, root); + defer ck.close(); + // the loader and preflight agree this head comes from the model shards, not the main table + try expectSameSource(try preflightSource(root), ck.mtp_source); + try std.testing.expect(!ck.mtp_source.?.side); + try std.testing.expect(!ck.mtp_source.?.main); + try std.testing.expectEqual(@as(u64, 2048 + 50432), try preflightDeviceBytes(root)); + var m = (try ck.mtp()) orelse return error.TestUnexpectedResult; + defer m.deinit(); + try std.testing.expect(m.owned != null); +} + +test "MTP source: a side file of mtp tensors with neither first norm is refused by the loader and preflight" { + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + var body = File.init(); + defer body.deinit(); + try body.put(M ++ "embed_tokens.weight", "BF16", &.{ 16, 64 }); + try body.write(tmp.dir, "model.safetensors"); + // a head's projections without `norm_e` or `pre_fc_norm_embedding`: no head `readMtp` could read + var side = File.init(); + defer side.deinit(); + try side.put("language_model.mtp.fc.weight", "BF16", &.{ 64, 64 }); + try side.put("language_model.mtp.norm.weight", "BF16", &.{64}); + try side.write(tmp.dir, "mtp.safetensors"); + try writeIndex(tmp.dir, &body, "model.safetensors"); + var conf: [1024]u8 = undefined; + try tmp.dir.writeFile(io, .{ .sub_path = "config.json", .data = try modeloptConfig(&conf) }); + const root = try rootOf(tmp); + defer gpa.free(root); + // main loaded this as "no head" while preflight counted the side file's bytes + try std.testing.expectError(error.MtpHeadWithoutNorm, checkpoint.Checkpoint.open(gpa, io, root)); + try std.testing.expectError(error.MtpHeadWithoutNorm, preflightSource(root)); + try std.testing.expectError(error.MtpHeadWithoutNorm, table.deviceBytesAt(gpa, io, root)); +} + +test "MTP source: a stray mtp tensor in the model shards is refused by the loader and preflight" { + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + var body = File.init(); + defer body.deinit(); + try body.put(M ++ "embed_tokens.weight", "BF16", &.{ 16, 64 }); + try body.put("mtp.fc.weight", "BF16", &.{ 64, 64 }); + try body.write(tmp.dir, "model.safetensors"); + try writeIndex(tmp.dir, &body, "model.safetensors"); + try tmp.dir.writeFile(io, .{ .sub_path = "config.json", .data = config }); + const root = try rootOf(tmp); + defer gpa.free(root); + // any `mtp.` key made the main table the source, and the loader then failed on a missing norm + try std.testing.expectError(error.MtpHeadWithoutNorm, checkpoint.Checkpoint.open(gpa, io, root)); + try std.testing.expectError(error.MtpHeadWithoutNorm, preflightSource(root)); + try std.testing.expectError(error.MtpHeadWithoutNorm, table.textBytes(gpa, io, root, 0)); +} diff --git a/zig/src/families/qwen3_5/weights/nvfp4_shape_test.zig b/zig/src/families/qwen3_5/weights/nvfp4_shape_test.zig new file mode 100644 index 00000000000..59056be048e --- /dev/null +++ b/zig/src/families/qwen3_5/weights/nvfp4_shape_test.zig @@ -0,0 +1,42 @@ +//! NVFP4 shapes from header-only safetensors files: an empty tensor's width can be anything, so no product overflows. +const std = @import("std"); +const core = @import("core"); +const nvfp4 = core.quant.nvfp4; + +const io = std.testing.io; +const gpa = std.testing.allocator; + +/// `.weight` U8 and `.weight_scale` E4M3 of these shapes, both empty, and a finite one-value F32 global. +fn reason(weight: [2]u64, scale: [2]u64) !?[]const u8 { + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + const header = try std.fmt.allocPrint(gpa, "{{\"p.weight\":{{\"dtype\":\"U8\",\"shape\":[{d},{d}],\"data_offsets\":[0,0]}}," ++ + "\"p.weight_scale\":{{\"dtype\":\"F8_E4M3\",\"shape\":[{d},{d}],\"data_offsets\":[0,0]}}," ++ + "\"p.weight_scale_2\":{{\"dtype\":\"F32\",\"shape\":[1],\"data_offsets\":[0,4]}}}}", .{ weight[0], weight[1], scale[0], scale[1] }); + defer gpa.free(header); + const bytes = try gpa.alloc(u8, 8 + header.len + 4); + defer gpa.free(bytes); + std.mem.writeInt(u64, bytes[0..8], header.len, .little); + @memcpy(bytes[8..][0..header.len], header); + std.mem.writeInt(u32, bytes[8 + header.len ..][0..4], @bitCast(@as(f32, 1)), .little); + try tmp.dir.writeFile(io, .{ .sub_path = "model.safetensors", .data = bytes }); + const path = try tmp.dir.realPathFileAlloc(io, "model.safetensors", gpa); + defer gpa.free(path); + var f = try core.safetensors.File.open(gpa, io, path); + defer f.close(io); + return nvfp4.unfit(f.get("p.weight").?, f.get("p.weight_scale").?, f.get("p.weight_scale_2").?); +} + +// What nvfp4.read refuses by the weight's name; each case below wrapped a product or a u32 cast before the guard +test "NVFP4 shapes: an empty weight or scale too wide for its products is refused by name, not wrapped" { + const too_wide = "an NVFP4 weight's K is past 2^64"; + const scales = "NVFP4 scales are [N, K/16]"; + const u32_bound = "an NVFP4 weight's N and K are each below 2^32"; + // K = 2 x 2^63 wraps to 0, a multiple of 32 + try std.testing.expectEqualStrings(too_wide, (try reason(.{ 0, 1 << 63 }, .{ 0, 0 })).?); + // the scale's 2^60 groups of 16 wrap to K = 0 + try std.testing.expectEqualStrings(scales, (try reason(.{ 0, 0 }, .{ 0, 1 << 60 })).?); + // N and K past what the kernels take as u32 + try std.testing.expectEqualStrings(u32_bound, (try reason(.{ 1 << 33, 0 }, .{ 1 << 33, 0 })).?); + try std.testing.expectEqualStrings(u32_bound, (try reason(.{ 0, 1 << 32 }, .{ 0, 1 << 29 })).?); +} diff --git a/zig/src/families/qwen3_5/weights/projection.zig b/zig/src/families/qwen3_5/weights/projection.zig index 31040751526..57cbc9bd0b5 100644 --- a/zig/src/families/qwen3_5/weights/projection.zig +++ b/zig/src/families/qwen3_5/weights/projection.zig @@ -6,6 +6,7 @@ const table = @import("table.zig"); const host = @import("host.zig"); const convert = quant.convert; +const modelopt = @import("modelopt.zig"); const Tensor = table.Tensor; const Table = table.Table; pub const Error = table.Error || convert.Error || error{UnexpectedTensor}; @@ -57,15 +58,19 @@ pub fn squeezed(w: Tensor) ?Tensor { /// `_packed`: a projection in whichever format its tensors are in; a bf16 one's are BF16 as stored, or fp32 widened. pub fn projection(a: std.mem.Allocator, t: *const Table, key: []const u8) !host.Projection { + if (modelopt.algo(t, key)) |what| return modelopt.read(a, t, key, what); + // a ModelOpt checkpoint's text layers read dense; its vision tower keeps rocBLAS (1,152 x 4,304 is no tile) + const tower = std.mem.startsWith(u8, key, "model.visual.") or std.mem.startsWith(u8, key, "vision_tower."); + if (t.quant == .bf16 and t.modelopt and !tower) return .{ .dense = try quant.dense.readStored(a, t, key) }; if (t.quant == .bf16 and t.widen) { _ = try quant.bf16.read(a, t, key); // the same dtype and rank checks return .{ .dense = try quant.dense.read(a, t, key) }; } if (t.quant == .bf16) return .{ .bf16 = try quant.bf16.read(a, t, key) }; - return quant.read(a, t, key); + return host.read(a, t, key); } /// `_halves`: a fused [embedding | hidden] projection split in two along K, words and group tables alike. pub fn halves(a: std.mem.Allocator, fused: host.Projection) ![2]host.Projection { - return quant.halves(a, fused); + return host.halves(a, fused); } diff --git a/zig/src/families/qwen3_5/weights/slicing.zig b/zig/src/families/qwen3_5/weights/slicing.zig index e0310fda544..03e9d5d15f3 100644 --- a/zig/src/families/qwen3_5/weights/slicing.zig +++ b/zig/src/families/qwen3_5/weights/slicing.zig @@ -25,12 +25,12 @@ pub fn localSpec(s: config.Spec, r: Rank) Error!config.Spec { /// `_rows`: output rows `spans` of a projection, the share of a column-split one. fn sliceRows(a: Allocator, p: host.Projection, spans: []const Span) Error!host.Projection { - return quant.sliceRows(a, p, spans); + return host.sliceRows(a, p, spans); } /// `_cols`: one rank's whole input groups of a row-split projection, whose fp32 outputs the ranks sum. fn cols(a: Allocator, p: host.Projection, r: Rank, what: []const u8) Error!host.Projection { - return quant.sliceCols(a, p, r, what); + return host.sliceCols(a, p, r, what); } /// This rank's rows of each segment of a concatenated output (q | k | v), each segment split evenly. diff --git a/zig/src/families/qwen3_5/weights/table.zig b/zig/src/families/qwen3_5/weights/table.zig index 7f2348f8f7b..873dbd3ec4c 100644 --- a/zig/src/families/qwen3_5/weights/table.zig +++ b/zig/src/families/qwen3_5/weights/table.zig @@ -24,6 +24,8 @@ pub const Table = struct { quant: formats.Config, /// A bf16 chat checkpoint's projections read as fp32 dense (row-invariant kernels), not as rocBLAS BF16. widen: bool = false, + /// A ModelOpt checkpoint's own bf16 layers (an lm_head, a linear) read dense: row-invariant, not rocBLAS. + modelopt: bool = false, /// Maps `paths` (later files win a repeated name, as the Python dict does). pub fn open(gpa: std.mem.Allocator, io: Io, paths: []const []const u8, strip: []const u8, quant: formats.Config) !Table { @@ -77,6 +79,12 @@ pub const Table = struct { return t.where.contains(key); } + /// Whether the table holds an MTP head: one of its first norms (`isMtpNorm`), as `Files.mtpSource` decides. + pub fn hasMtpNorm(t: *const Table) bool { + for (mtp_norms) |n| if (t.has(n)) return true; + return false; + } + /// The tensor under `key`, marked as used; a missing one is `error.MissingTensor`, logged by name. pub fn get(t: *const Table, key: []const u8) Error!Tensor { const w = t.where.get(key) orelse { @@ -159,30 +167,26 @@ pub const Files = struct { if (e.kind != .file and e.kind != .sym_link) continue; if (!std.mem.endsWith(u8, e.name, ".safetensors")) continue; const path = try std.fs.path.join(a, &.{ dir, e.name }); - if (std.mem.startsWith(u8, e.name, "mtp")) try side.append(a, path); - if (!containsLower(e.name, "mtp")) try model.append(a, path); + if (isMtpName(e.name)) try side.append(a, path) else try model.append(a, path); } - const less = struct { - fn f(_: void, x: []const u8, y: []const u8) bool { - return std.mem.order(u8, x, y) == .lt; - } - }.f; - std.mem.sort([]const u8, model.items, {}, less); - std.mem.sort([]const u8, side.items, {}, less); + std.mem.sort([]const u8, model.items, {}, lessPath); + std.mem.sort([]const u8, side.items, {}, lessPath); return .{ .arena = arena, .model = model.items, .side = side.items }; } /// The shards of `model.safetensors.index.json` (else `model.safetensors`) holding a text-tower or head tensor. - pub fn indexed(gpa: std.mem.Allocator, io: Io, dir: []const u8) !Files { + pub fn indexed(gpa: std.mem.Allocator, io: Io, dir: []const u8, mtp: bool) !Files { var arena: std.heap.ArenaAllocator = .init(gpa); errdefer arena.deinit(); const a = arena.allocator(); + var side: std.ArrayList([]const u8) = .empty; + if (mtp) try mtpSide(a, io, dir, &side); const index = try std.fs.path.join(a, &.{ dir, "model.safetensors.index.json" }); const text = Io.Dir.cwd().readFileAlloc(io, index, a, .limited(1 << 26)) catch |e| switch (e) { error.FileNotFound => { const one = try a.alloc([]const u8, 1); one[0] = try std.fs.path.join(a, &.{ dir, "model.safetensors" }); - return .{ .arena = arena, .model = one, .side = &.{} }; + return .{ .arena = arena, .model = one, .side = try side.toOwnedSlice(a) }; }, else => return e, }; @@ -192,24 +196,94 @@ pub const Files = struct { var names: std.StringArrayHashMapUnmanaged(void) = .empty; for (map.?.object.keys(), map.?.object.values()) |k, v| { if (v != .string or std.mem.indexOfScalar(u8, v.string, '/') != null) return error.NoSafetensors; + // one classification rule for the side set and the index: an MTP-named file belongs to the head + if (mtp and isMtpName(v.string)) continue; // a shard of only vision tensors is not the backbone's: it need not exist or parse - if (std.mem.startsWith(u8, k, "model.language_model.") or std.mem.startsWith(u8, k, "lm_head.")) try names.put(a, v.string, {}); + const tower = std.mem.startsWith(u8, k, "model.language_model.") or std.mem.startsWith(u8, k, "lm_head."); + const head = mtp and std.mem.startsWith(u8, k, "mtp."); + if (tower or head) try names.put(a, v.string, {}); } const model = try a.alloc([]const u8, names.count()); for (model, names.keys()) |*m, n| m.* = try std.fs.path.join(a, &.{ dir, n }); - std.mem.sort([]const u8, model, {}, struct { - fn f(_: void, x: []const u8, y: []const u8) bool { - return std.mem.order(u8, x, y) == .lt; - } - }.f); - return .{ .arena = arena, .model = model, .side = &.{} }; + std.mem.sort([]const u8, model, {}, lessPath); + return .{ .arena = arena, .model = model, .side = try side.toOwnedSlice(a) }; + } + + /// The one MTP source: side files, then model shards, holding a first norm (`isMtpNorm`); bare `mtp.` refused. + pub fn mtpSource(f: *const Files, gpa: std.mem.Allocator, io: Io) !?MtpSource { + if (f.side.len > 0) { + const side = try scanMtp(gpa, io, f.side); + if (side.own_norm or side.stripped_norm) return .{ .paths = f.side, .side = true, .main = false }; + if (side.stray) |path| return refuseMtp(path); + } + const model = try scanMtp(gpa, io, f.model); + // an unprefixed head is the main table's own; a `language_model.` one needs that strip + if (model.own_norm) return .{ .paths = f.model, .side = false, .main = true }; + if (model.stripped_norm) return .{ .paths = f.model, .side = false, .main = false }; + if (model.stray) |path| return refuseMtp(path); + return null; + } +}; + +/// The names a head's first norm takes, flash and gated: `readMtp` reads one of them for every head it accepts. +pub const mtp_norms = [_][]const u8{ "mtp.norm_e.weight", "mtp.pre_fc_norm_embedding.weight" }; + +/// Whether `key`, as the loader reads it (after any `language_model.` strip), is a head's first norm. +pub fn isMtpNorm(key: []const u8) bool { + for (mtp_norms) |n| if (std.mem.eql(u8, key, n)) return true; + return false; +} + +/// What a shard set holds of an MTP head: a first norm unprefixed or under the strip, and a file with any `mtp.` key. +const MtpScan = struct { own_norm: bool = false, stripped_norm: bool = false, stray: ?[]const u8 = null }; + +fn scanMtp(gpa: std.mem.Allocator, io: Io, paths: []const []const u8) !MtpScan { + var out: MtpScan = .{}; + for (paths) |path| { + var shard = try Shard.open(gpa, io, path); + defer shard.close(io); + var it = shard.names.iterator(); + while (it.next()) |kv| { + const key = kv.key_ptr.*; + if (isMtpNorm(key)) out.own_norm = true; + if (isMtpNorm(stripPrefix(key))) out.stripped_norm = true; + if (out.stray == null and isMtpKey(stripPrefix(key))) out.stray = path; + } } + return out; +} + +/// `mtp.` tensors with neither first norm: not a head the loader reads, so neither the loader nor preflight takes it. +fn refuseMtp(path: []const u8) error{MtpHeadWithoutNorm} { + std.log.warn("{s} holds mtp. tensors but neither {s} nor {s}: not a whole MTP head, so the checkpoint is refused", .{ path, mtp_norms[0], mtp_norms[1] }); + return error.MtpHeadWithoutNorm; +} + +/// Drops the side file's `language_model.` strip prefix, as `Table.open(.., "language_model.", ..)` does. +fn stripPrefix(key: []const u8) []const u8 { + return if (std.mem.startsWith(u8, key, "language_model.")) key["language_model.".len..] else key; +} + +/// Head names as the loader reads them: the MTP projection prefix, under either checkpoint's naming. +fn isMtpKey(key: []const u8) bool { + return std.mem.startsWith(u8, key, "mtp."); +} + +/// Which set of shards the MTP head is read from: the side files, the model shards, or the main table. +pub const MtpSource = struct { + paths: []const []const u8, + /// Whether the head came from a side file (its keys are `language_model.`-prefixed). + side: bool, + /// Whether the already-open main table is itself the source. + main: bool, }; -/// The bytes of a bf16 checkpoint's text tower and head (its index's shards): what loads, not the vision tower. -pub fn textBytes(gpa: std.mem.Allocator, io: Io, dir: []const u8) !u64 { - var files = try Files.indexed(gpa, io, dir); +/// The bytes of a bf16 checkpoint's text tower and head as stored; a declared `mtp_layers` means the loader refuses it. +pub fn textBytes(gpa: std.mem.Allocator, io: Io, dir: []const u8, mtp_layers: usize) !u64 { + var files = try Files.indexed(gpa, io, dir, false); defer files.deinit(); + const source = if (mtp_layers == 0) try files.mtpSource(gpa, io) else null; + const own = if (source) |s| s.main else false; var total: u64 = 0; for (files.model) |path| { var shard = try Shard.open(gpa, io, path); @@ -217,13 +291,117 @@ pub fn textBytes(gpa: std.mem.Allocator, io: Io, dir: []const u8) !u64 { var it = shard.names.iterator(); while (it.next()) |kv| { const key = kv.key_ptr.*; - if (!std.mem.startsWith(u8, key, "model.language_model.") and !std.mem.eql(u8, key, "lm_head.weight")) continue; + const text = std.mem.startsWith(u8, key, "model.language_model."); + const head = std.mem.startsWith(u8, key, "lm_head."); + if (!text and !head) { + // a head these shards hold counts only when the main table is its source, and once + if (!own or !isMtpKey(key)) continue; + } total += kv.value_ptr.end - kv.value_ptr.begin; } } + if (source) |s| { + if (!s.main) total += try headBytes(gpa, io, s.paths, false); + } + return total; +} + +/// Selects the MTP source once, as `Checkpoint.open` does, then counts the device bytes. +pub fn deviceBytesAt(gpa: std.mem.Allocator, io: Io, dir: []const u8) !u64 { + var files = try Files.indexed(gpa, io, dir, true); + defer files.deinit(); + return deviceBytes(gpa, io, dir, try files.mtpSource(gpa, io)); +} + +/// The bytes a ModelOpt checkpoint takes on the device: codes as stored, a widened tensor at F32, a table at BF16. +pub fn deviceBytes(gpa: std.mem.Allocator, io: Io, dir: []const u8, source: ?MtpSource) !u64 { + var files = try Files.indexed(gpa, io, dir, true); + defer files.deinit(); + const own = if (source) |s| s.main else false; + var total: u64 = 0; + for (files.model) |path| { + var shard = try Shard.open(gpa, io, path); + defer shard.close(io); + var it = shard.names.iterator(); + while (it.next()) |kv| { + const key = kv.key_ptr.*; + if (!loaded(key)) continue; + // the head is counted from its own source below, never from these shards as well + if (!own and (isMtpKey(key) or isMtpKey(stripPrefix(key)))) continue; + total += deviceSize(key, kv.value_ptr.*); + } + } + if (source) |s| { + if (!s.main) total += try headBytes(gpa, io, s.paths, true); + } + return total; +} + +/// The selected head's bytes, one entry per name as `Table.open` maps repeats; `device` counts the device copy. +fn headBytes(gpa: std.mem.Allocator, io: Io, paths: []const []const u8, comptime device: bool) !u64 { + var arena: std.heap.ArenaAllocator = .init(gpa); + defer arena.deinit(); + const a = arena.allocator(); + var bytes: std.StringHashMapUnmanaged(u64) = .empty; + defer bytes.deinit(a); + for (paths) |path| { + var shard = try Shard.open(gpa, io, path); + defer shard.close(io); + var it = shard.names.iterator(); + while (it.next()) |kv| { + const name = stripPrefix(kv.key_ptr.*); + if (!isMtpKey(name)) continue; + const stored: u64 = @intCast(kv.value_ptr.end - kv.value_ptr.begin); + const gop = try bytes.getOrPut(a, try a.dupe(u8, name)); + gop.value_ptr.* = if (device) deviceSize(name, kv.value_ptr.*) else stored; + } + } + var total: u64 = 0; + var bit = bytes.valueIterator(); + while (bit.next()) |v| total += v.*; return total; } +/// Whether a ModelOpt checkpoint's loader reads this tensor: its text tower, its head, or the MTP head. +fn loaded(key: []const u8) bool { + return std.mem.startsWith(u8, key, "model.language_model.") or + std.mem.startsWith(u8, key, "lm_head.") or + isMtpKey(key) or isMtpKey(stripPrefix(key)); +} + +/// The bytes one tensor takes on the device: a norm, an `A_log`, a `dt_bias` or a conv widens to F32. +fn deviceSize(key: []const u8, e: st.Entry) u64 { + const stored: u64 = @intCast(e.end - e.begin); + const values = stored / @as(u64, @intCast(e.dtype.size())); + // an E4M3 group table is widened to BF16 at read, and a code's own byte stays + if (std.mem.endsWith(u8, key, ".weight_scale")) return if (e.dtype == .f8_e4m3) 2 * values else stored; + return if (widened(key)) 4 * values else stored; +} + +/// Whether the loader reads this tensor through `projection.float`, `centred` or `conv`: an fp32 tensor on the device. +fn widened(key: []const u8) bool { + if (std.mem.endsWith(u8, key, "conv1d.weight")) return true; + if (std.mem.endsWith(u8, key, ".A_log") or std.mem.endsWith(u8, key, ".dt_bias")) return true; + // every RMS weight, including `pre_fc_norm_embedding` and `norm_e`, reads through float or centred + return std.mem.endsWith(u8, key, ".weight") and std.mem.indexOf(u8, key, "norm") != null; +} + +/// The `mtp*.safetensors` files in `dir`, sorted: a head shipped beside the model's own shards. +fn mtpSide(a: std.mem.Allocator, io: Io, dir: []const u8, out: *std.ArrayList([]const u8)) !void { + var d = Io.Dir.cwd().openDir(io, dir, .{ .iterate = true }) catch |e| switch (e) { + error.FileNotFound => return, + else => return e, + }; + defer d.close(io); + var it = d.iterate(); + while (try it.next(io)) |e| { + if (e.kind != .file and e.kind != .sym_link) continue; + if (!isMtpName(e.name)) continue; + try out.append(a, try std.fs.path.join(a, &.{ dir, e.name })); + } + std.mem.sort([]const u8, out.items, {}, lessPath); +} + fn containsLower(name: []const u8, needle: []const u8) bool { var i: usize = 0; while (i + needle.len <= name.len) : (i += 1) { @@ -232,6 +410,15 @@ fn containsLower(name: []const u8, needle: []const u8) bool { return false; } +/// One classification for the side collector, the directory listing and the index's weight map. +fn isMtpName(name: []const u8) bool { + return std.mem.endsWith(u8, name, ".safetensors") and containsLower(name, "mtp"); +} + +fn lessPath(_: void, x: []const u8, y: []const u8) bool { + return std.mem.order(u8, x, y) == .lt; +} + test "mtp in a file name keeps it out of the model's files" { try std.testing.expect(containsLower("Model-MTP-4bit.safetensors", "mtp")); try std.testing.expect(!containsLower("model-00001-of-00004.safetensors", "mtp")); diff --git a/zig/src/hip/kernel_tests.zig b/zig/src/hip/kernel_tests.zig index ec8b407a19d..a58fc20eccb 100644 --- a/zig/src/hip/kernel_tests.zig +++ b/zig/src/hip/kernel_tests.zig @@ -64,6 +64,8 @@ test { _ = @import("kernel_tests/ops.zig"); _ = @import("kernel_tests/conv_split.zig"); _ = @import("kernel_tests/dense.zig"); + _ = @import("kernel_tests/nvfp4.zig"); + _ = @import("kernel_tests/fp8.zig"); _ = @import("kernel_tests/silu_fuse.zig"); _ = @import("kernel_tests/argmax.zig"); _ = @import("kernel_tests/embed.zig"); diff --git a/zig/src/hip/kernel_tests/fp8.zig b/zig/src/hip/kernel_tests/fp8.zig new file mode 100644 index 00000000000..8c8c4b774c4 --- /dev/null +++ b/zig/src/hip/kernel_tests/fp8.zig @@ -0,0 +1,134 @@ +//! ModelOpt FP8's product against the format's float64 reference, at every row count the engine serves. + +const std = @import("std"); +const rig = @import("rig.zig"); +const launch = @import("../launches/fp8.zig"); +const quant = @import("core").quant; + +const Rig = rig.Rig; +const gpa = rig.gpa; +const at = rig.at; + +/// A projection as ModelOpt stores an FP8 one: E4M3 codes one a byte, one f32 scale a projection. +const Proj = struct { + codes: []u8, + scale: f32, + n: usize, + k: usize, + + fn init(a: std.mem.Allocator, rng: *rig.Rng, n: usize, k: usize, scale: f32) !Proj { + const codes = try a.alloc(u8, n * k); + for (codes) |*c| { + var b: u8 = @intCast(rng.next() & 0xff); + if (b & 0x7f == 0x7f) b &= 0xfe; // E4M3's NaN codes are refused at read + c.* = b; + } + return .{ .codes = codes, .scale = scale, .n = n, .k = k }; + } + + fn deinit(p: Proj) void { + gpa.free(p.codes); + } +}; + +/// `hx`'s rows times `p`, f32 out, against the format's f64 values and the bound the kernel's own chain allows. +fn product(t: *Rig, p: Proj, hx: []const u16) ![]f32 { + const rows = hx.len / p.k; + const want = try gpa.alloc(f64, rows * p.n); + defer gpa.free(want); + const mag = try gpa.alloc(f64, rows * p.n); + defer gpa.free(mag); + for (0..rows) |r| { + for (0..p.n) |c| { + var acc: f64 = 0; + var abs: f64 = 0; + for (0..p.k) |j| { + const term = t.value(hx[r * p.k + j]) * quant.fp8.e4m3(p.codes[c * p.k + j]); + acc += term; + abs += @abs(term); + } + want[r * p.n + c] = acc * @as(f64, p.scale); + mag[r * p.n + c] = abs * @as(f64, p.scale); + } + } + + var x = try t.upload(hx); + defer x.free(); + var codes = try t.upload(p.codes); + defer codes.free(); + const one = [_]f32{p.scale}; + var scale = try t.upload(std.mem.sliceAsBytes(&one)); + defer scale.free(); + var out = try t.alloc(rows * p.n * 4); + defer out.free(); + + const w: launch.Weight = .{ + .x = at(x), + .codes = at(codes), + .scale = at(scale), + .out = at(out), + .m = @intCast(rows), + .n = @intCast(p.n), + .k = @intCast(p.k), + }; + try launch.Kernels.gemmGo(&t.on.fp8, &t.r, w, t.stream.handle); + try t.stream.synchronize(); + + const bits = try rig.download(u32, out); + errdefer gpa.free(bits); + const got: []f32 = @ptrCast(bits); + // the kernel's chain: k fmaf into the sum, then one multiply by the scale + const u = std.math.pow(f64, 2, -24); + const per_element = @as(f64, @floatFromInt(p.k + 1)) * u; + var worst: f64 = 0; + for (want, 0..) |wv, i| { + const tol = per_element * mag[i]; + if (mag[i] > 0) worst = @max(worst, @abs(@as(f64, got[i]) - wv) / tol); + if (@abs(@as(f64, got[i]) - wv) > tol) { + std.debug.print("fp8 {d}x{d} rows {d}: [{d}, {d}] is {d} against {d}, bound {d}\n", .{ p.n, p.k, rows, i / p.n, i % p.n, got[i], wv, tol }); + return error.TestUnexpectedResult; + } + } + std.debug.print("fp8 {d}x{d} rows {d}: worst |got - want| is {d:.3} of the derived bound\n", .{ p.n, p.k, rows, worst }); + return got; +} + +test "FP8: the product holds the format reference at one row, at three and at five" { + const t = try Rig.open(1 << 16); + defer t.close(); + var rng: rig.Rng = .{ .state = 0x6A31C7 }; + for ([_][3]usize{ .{ 64, 64, 0 }, .{ 160, 128, 1 }, .{ 48, 96, 2 } }) |shape| { + // one global of each kind: a power of two, an awkward f32, and one below it + const scale: f32 = switch (shape[2]) { + 0 => 0.25, + 1 => 0.3, + else => 0.01171875, + }; + const p = try Proj.init(gpa, &rng, shape[0], shape[1], scale); + defer p.deinit(); + for ([_]usize{ 1, 3, 5 }) |rows| { + const hx = try gpa.alloc(u16, rows * p.k); + defer gpa.free(hx); + for (hx) |*v| v.* = t.bits(rng.unit()); + const got = try product(t, p, hx); + gpa.free(got); + } + } +} + +test "FP8: a row's bits are the same alone and in a round of seventeen" { + const t = try Rig.open(1 << 16); + defer t.close(); + var rng: rig.Rng = .{ .state = 0x1D4B93 }; + // K above a chunk, so the round's tile folds two partials where the one row folds one + const p = try Proj.init(gpa, &rng, 96, 192, 0.375); + defer p.deinit(); + const hx = try gpa.alloc(u16, 17 * p.k); + defer gpa.free(hx); + for (hx) |*v| v.* = t.bits(rng.unit()); + const alone = try product(t, p, hx[0..p.k]); + defer gpa.free(alone); + const round = try product(t, p, hx); + defer gpa.free(round); + try std.testing.expectEqualSlices(f32, alone, round[0..p.n]); +} diff --git a/zig/src/hip/kernel_tests/nvfp4.zig b/zig/src/hip/kernel_tests/nvfp4.zig new file mode 100644 index 00000000000..887c764af9b --- /dev/null +++ b/zig/src/hip/kernel_tests/nvfp4.zig @@ -0,0 +1,164 @@ +//! ModelOpt NVFP4's product against the format's float64 reference, at every row count the engine serves. + +const std = @import("std"); +const rig = @import("rig.zig"); +const launch = @import("../launches/nvfp4.zig"); +const quant = @import("core").quant; + +const Rig = rig.Rig; +const gpa = rig.gpa; +const at = rig.at; + +/// A projection as the checkpoint stores it: e2m1 nibbles, an E4M3 scale a 16 inputs, one global scale. +const Proj = struct { + codes: []u8, + scales: []u8, + global: f32, + n: usize, + k: usize, + + fn init(a: std.mem.Allocator, rng: *rig.Rng, n: usize, k: usize, global: f32) !Proj { + const codes = try a.alloc(u8, n * k / 2); + for (codes) |*c| c.* = @intCast(rng.next() & 0xff); + const scales = try a.alloc(u8, n * (k / quant.nvfp4.group)); + // E4M3 in [0.5, 1.875]: every byte holds a finite positive value + for (scales) |*s| s.* = @intCast(0x30 + (rng.next() & 0x0f)); + return .{ .codes = codes, .scales = scales, .global = global, .n = n, .k = k }; + } + + fn deinit(p: Proj) void { + gpa.free(p.codes); + gpa.free(p.scales); + } +}; + +/// The ModelOpt tensors behind one key, as the loader reads them. +const Fake = struct { + w: quant.Tensor, + s: quant.Tensor, + g: quant.Tensor, + + pub fn get(f: *const Fake, key: []const u8) !quant.Tensor { + if (std.mem.endsWith(u8, key, ".weight")) return f.w; + if (std.mem.endsWith(u8, key, ".weight_scale_2")) return f.g; + if (std.mem.endsWith(u8, key, ".weight_scale")) return f.s; + return error.MissingTensor; + } + + pub fn has(f: *const Fake, key: []const u8) bool { + _ = f; + return std.mem.endsWith(u8, key, ".weight_scale_2"); + } +}; + +/// `hx`'s rows (each `k` wide, the activation's bits) times `p`, f32 out: the one product kernel. +fn product(t: *Rig, p: Proj, hx: []const u16) ![]f32 { + const rows = hx.len / p.k; + var arena: std.heap.ArenaAllocator = .init(gpa); + defer arena.deinit(); + const a = arena.allocator(); + // the projection through the format's own reader, so the oracle reads the table the engine uploads + const fake: Fake = .{ + .w = .{ .dtype = .u8, .rank = 2, .shape = .{ p.n, p.k / 2, 1, 1, 1 }, .bytes = p.codes }, + .s = .{ .dtype = .f8_e4m3, .rank = 2, .shape = .{ p.n, p.k / quant.nvfp4.group, 1, 1, 1 }, .bytes = p.scales }, + .g = .{ .dtype = .f32, .rank = 1, .shape = .{ 1, 1, 1, 1, 1 }, .bytes = std.mem.sliceAsBytes((&[_]f32{p.global})[0..]) }, + }; + const h = try quant.nvfp4.read(a, &fake, "p"); + const wq = try a.alloc(f64, p.n * p.k); + try quant.nvfp4.reference(h, wq); + // the product is the test's own f64 sum: the format reads back exactly, and the product rounds once to f32 + const want = try a.alloc(f64, rows * p.n); + const mag = try a.alloc(f64, rows * p.n); + for (0..rows) |r| { + for (0..p.n) |c| { + var acc: f64 = 0; + var abs: f64 = 0; + for (0..p.k) |j| { + const term = t.value(hx[r * p.k + j]) * wq[c * p.k + j]; + acc += term; + abs += @abs(term); + } + want[r * p.n + c] = acc; + mag[r * p.n + c] = abs; + } + } + + var x = try t.upload(hx); + defer x.free(); + var codes = try t.upload(p.codes); + defer codes.free(); + var scale = try t.upload(std.mem.bytesAsSlice(u16, h.scale.bytes)); + defer scale.free(); + var out = try t.alloc(rows * p.n * 4); + defer out.free(); + + const w: launch.Weight = .{ + .x = at(x), + .words = at(codes), + .scale = .{ .p = at(scale), .kind = @backingInt(quant.Tables.bf16) }, + .out = at(out), + .m = @intCast(rows), + .n = @intCast(p.n), + .k = @intCast(p.k), + .global = p.global, + }; + try launch.Kernels.gemmGo(&t.on.nvfp4, &t.r, w, t.stream.handle); + try t.stream.synchronize(); + + const bits = try rig.download(u32, out); + errdefer gpa.free(bits); + const got: []f32 = @ptrCast(bits); + // the product's own chain: k fmaf into a group's q, then one a group into acc, then the global once + const u = std.math.pow(f64, 2, -24); + const per_element = @as(f64, @floatFromInt(p.k + p.k / quant.nvfp4.group)) * u; + var worst: f64 = 0; + for (want, 0..) |wv, i| { + const tol = per_element * mag[i]; + if (mag[i] > 0) worst = @max(worst, @abs(@as(f64, got[i]) - wv) / tol); + if (@abs(@as(f64, got[i]) - wv) > tol) { + std.debug.print("nvfp4 {d}x{d} rows {d} x[0]={d} wq[0]={d} wq[1]={d} want[{d}]={d} got={d}\n", .{ p.n, p.k, rows, t.value(hx[0]), wq[0], wq[1], i, wv, got[i] }); + return error.TestUnexpectedResult; + } + } + std.debug.print("nvfp4 {d}x{d} rows {d}: worst |got - want| is {d:.3} of the derived bound\n", .{ p.n, p.k, rows, worst }); + return got; +} + +fn draw(a: std.mem.Allocator, t: *const Rig, rng: *rig.Rng, rows: usize, k: usize) ![]u16 { + const hx = try a.alloc(u16, rows * k); + for (hx) |*v| v.* = t.bits(rng.unit()); + return hx; +} + +test "NVFP4: the product holds the format reference at one row, at three and at five" { + const t = try Rig.open(1 << 16); + defer t.close(); + var rng: rig.Rng = .{ .state = 0x4F9D21 }; + for ([_][2]usize{ .{ 64, 64 }, .{ 160, 128 } }) |shape| { + // a global scale that is no power of two, so the multiply is exercised and not a shift + const p = try Proj.init(gpa, &rng, shape[0], shape[1], if (shape[0] == 64) 0.25 else 0.3); + defer p.deinit(); + for ([_]usize{ 1, 3, 5 }) |rows| { + const hx = try draw(gpa, t, &rng, rows, p.k); + defer gpa.free(hx); + const got = try product(t, p, hx); + gpa.free(got); + } + } +} + +test "NVFP4: a row's bits are the same alone and in a round of seventeen" { + const t = try Rig.open(1 << 16); + defer t.close(); + var rng: rig.Rng = .{ .state = 0x51A6E7 }; + // K above a chunk, so the round's tile folds two chunks where the one row folds one + const p = try Proj.init(gpa, &rng, 96, 192, 0.5); + defer p.deinit(); + const hx = try draw(gpa, t, &rng, 17, p.k); + defer gpa.free(hx); + const alone = try product(t, p, hx[0..p.k]); + defer gpa.free(alone); + const round = try product(t, p, hx); + defer gpa.free(round); + try std.testing.expectEqualSlices(f32, alone, round[0..p.n]); +} diff --git a/zig/src/hip/launches.zig b/zig/src/hip/launches.zig index 4fff2b4ad37..fe2769c40b2 100644 --- a/zig/src/hip/launches.zig +++ b/zig/src/hip/launches.zig @@ -9,6 +9,8 @@ const Function = @import("module.zig").Function; const Stream = @import("stream.zig").Stream; const caps = @import("caps.zig"); const affine = @import("launches/affine.zig"); +const nvfp4 = @import("launches/nvfp4.zig"); +const fp8 = @import("launches/fp8.zig"); pub const dense = @import("launches/dense.zig"); pub const item = @import("launches/matrix_item.zig"); @@ -108,6 +110,10 @@ pub const Launcher = struct { affine: affine.Kernels, /// The BF16 dense GEMM (raw BF16 weights through the dot2 GEMM tile). dense: dense.Kernels, + /// ModelOpt NVFP4: one product kernel for a prompt's rows and a round's, weights decoded in flight. + nvfp4: nvfp4.Kernels, + /// ModelOpt FP8: the same product, E4M3 codes decoded in flight and one scale a projection. + fp8: fp8.Kernels, /// Flash Next's kernels: its residual streams, n-gram rows, indexer and sparse attention. fnx: flashnext.Fns, /// Nemotron's Mamba-2 mixer kernels. @@ -359,6 +365,8 @@ pub const Launcher = struct { const chip = caps.Caps.of(kernels.arch) orelse return error.Invalid; l.affine = try affine.Kernels.load(tiles, dot2, chip, choices.products); l.dense = try dense.Kernels.load(tiles, chip.act == .bf16, chip.matrix == .wmma12, choices.products.matrix); + l.nvfp4 = try nvfp4.Kernels.load(tiles); + l.fp8 = try fp8.Kernels.load(tiles); try l.affine.fillByteLut(r, dot2); l.fnx = try flashnext.Fns.load(l.mods[@backingInt(kernels.Group.flashnext)]); return l; diff --git a/zig/src/hip/launches/fp8.zig b/zig/src/hip/launches/fp8.zig new file mode 100644 index 00000000000..4a65ce40397 --- /dev/null +++ b/zig/src/hip/launches/fp8.zig @@ -0,0 +1,63 @@ +//! quant/fp8_tiles.hpp's ModelOpt FP8 product: E4M3 codes decoded in flight, summed and scaled in f32. + +const std = @import("std"); +const abi = @import("../abi.zig"); +const runtime = @import("../runtime.zig"); +const hl = @import("../launch.zig"); +const Module = @import("../module.zig").Module; +const Function = @import("../module.zig").Function; +const util = @import("util.zig"); + +const Error = runtime.Error; +fn cdiv(n: c_int, by: c_int) c_uint { + return @intCast(@divTrunc(n + by - 1, by)); +} + +/// quant/fp8_tiles.hpp's ModelFp8: the stored E4M3 codes, the per-projection scale, and the product. +pub const Weight = extern struct { + x: u64, + codes: u64, + scale: u64, + out: u64, + m: c_int, + n: c_int, + k: c_int, +}; + +/// One byte a weight, an E4M3 code. +pub const bits: c_int = 8; + +/// Threads a block: the product's one output element a thread. +const threads: c_int = 256; + +comptime { + // quant/fp8_tiles.hpp's ModelFp8, field for field: x, codes, scale, out, m, n, k + std.debug.assert(@sizeOf(Weight) == 48); +} + +pub const Kernels = struct { + gemm: Function, + + /// `tiles` is dot2_tiles.hip's module, where every build carries it. + pub fn load(tiles: Module) Error!Kernels { + return .{ .gemm = try tiles.function("tf_fp8_gemm") }; + } + + /// The product `out` f32 (m, n): one call for a prompt's rows and a round's. + pub fn gemmGo(k: *const Kernels, r: *const runtime.Runtime, a: Weight, s: abi.Stream) Error!void { + if (a.m <= 0 or a.n <= 0 or a.k <= 0) return error.Invalid; + var args: hl.Args = .{}; + try args.add(a); + // a 64 x 64 block a launch: one an output tile, so a column's weights load once for the block's rows + try go(r, k.gemm, .{ .x = cdiv(a.n, 64), .y = cdiv(a.m, 64) }, .{ .x = @intCast(threads) }, s, &args); + } + + fn go(r: *const runtime.Runtime, f: Function, grid: hl.Dim3, block: hl.Dim3, s: abi.Stream, args: *hl.Args) Error!void { + if (s == util.counting) return; + try hl.launch(f, .{ .grid = grid, .block = block }, .{ .r = r, .handle = s }, args); + } +}; + +test "the weight's layout is quant/fp8_tiles.hpp's" { + try std.testing.expectEqual(@as(usize, 48), @sizeOf(Weight)); +} diff --git a/zig/src/hip/launches/nvfp4.zig b/zig/src/hip/launches/nvfp4.zig new file mode 100644 index 00000000000..e458bee4913 --- /dev/null +++ b/zig/src/hip/launches/nvfp4.zig @@ -0,0 +1,101 @@ +//! ModelOpt NVFP4's product kernel: one call for a prompt's rows and a round's, weights decoded in flight. + +const std = @import("std"); +const abi = @import("../abi.zig"); +const runtime = @import("../runtime.zig"); +const hl = @import("../launch.zig"); +const Module = @import("../module.zig").Module; +const Function = @import("../module.zig").Function; +const util = @import("util.zig"); + +const Error = runtime.Error; +/// ceil(n / by) as a grid extent, as the MLX launches write it. +fn cdiv(n: c_int, by: c_int) c_uint { + return @intCast(@divTrunc(n + by - 1, by)); +} + +/// quant/mlx.hpp's GroupTable: the group scales' address and their kind (0 f32, 1 bf16, 2 f16). +pub const Table = extern struct { p: u64, kind: c_int }; + +/// quant/plan.hpp's Routing: this format runs one plain (m, n) product. +pub const Routing = extern struct { items: u64 = 0, members: u64 = 0, x_div: c_int = 1, first: c_int = 0 }; + +/// quant/nvfp4.hpp's Nvfp4: the codes (n, K/8 words), the group table and the one global scale. +pub const Weight = extern struct { + x: u64, + words: u64, + scale: Table, + out: u64, + m: c_int, + n: c_int, + k: c_int, + group: c_int = 16, + global: f32 = 1, +}; + +/// Four-bit codes, one scale a 16 inputs. +pub const bits: c_int = 4; +pub const group: c_int = 16; + +/// Threads a block: the product's one output element a thread. +const threads: c_int = 256; + +/// The widest round the column path serves, matching quant/nvfp4_tiles.hpp's tf_nvfp4_col4. +const narrow: c_int = 4; + +comptime { + // quant/nvfp4.hpp's Nvfp4, field for field: x, words, scale, out, m, n, k, group, global + std.debug.assert(@sizeOf(Table) == 16); + std.debug.assert(@sizeOf(Weight) == 64); +} + +pub const Kernels = struct { + gemm: Function, + col1: Function, + col2: Function, + col3: Function, + col4: Function, + + /// `tiles` is dot2_tiles.hip's module, where every build carries it. + pub fn load(tiles: Module) Error!Kernels { + return .{ + .gemm = try tiles.function("tf_nvfp4_gemm"), + .col1 = try tiles.function("tf_nvfp4_col1"), + .col2 = try tiles.function("tf_nvfp4_col2"), + .col3 = try tiles.function("tf_nvfp4_col3"), + .col4 = try tiles.function("tf_nvfp4_col4"), + }; + } + + /// The product `out` f32 (m, n): one call for a prompt's rows and a round's. + pub fn gemmGo(k: *const Kernels, r: *const runtime.Runtime, a: Weight, s: abi.Stream) Error!void { + if (a.m <= 0 or a.n <= 0 or a.k <= 0 or a.group != group) return error.Invalid; + if (@rem(a.k, a.group) != 0) return error.Invalid; + var args: hl.Args = .{}; + try args.add(a); + // A decode round takes the column path when K is whole chunks and a.m has a variant; else the tile. + const chunk: c_int = 64; + if (a.m <= narrow and @rem(a.k, chunk) == 0) { + const f = switch (a.m) { + 1 => k.col1, + 2 => k.col2, + 3 => k.col3, + else => k.col4, + }; + return go(r, f, .{ .x = cdiv(a.n, threads) }, .{ .x = @intCast(threads) }, s, &args); + } + // a 64 x 64 block a launch: one an output tile, so a column's weights load once for the block's rows + try go(r, k.gemm, .{ .x = cdiv(a.n, 64), .y = cdiv(a.m, 64) }, .{ .x = @intCast(threads) }, s, &args); + } + + /// Launches on `s`; the counting stream runs nothing. + fn go(r: *const runtime.Runtime, f: Function, grid: hl.Dim3, block: hl.Dim3, s: abi.Stream, args: *hl.Args) Error!void { + if (s == util.counting) return; + try hl.launch(f, .{ .grid = grid, .block = block }, .{ .r = r, .handle = s }, args); + } +}; + +test "the weight's layout is quant/nvfp4.hpp's" { + try std.testing.expectEqual(@as(usize, 64), @sizeOf(Weight)); + try std.testing.expectEqual(@as(usize, 16), @sizeOf(Table)); +} diff --git a/zig/src/hip/ops/project.zig b/zig/src/hip/ops/project.zig index 25dc648f448..60b1a97e423 100644 --- a/zig/src/hip/ops/project.zig +++ b/zig/src/hip/ops/project.zig @@ -1,4 +1,5 @@ //! The products on a projection of any format, dispatched on its tag; `affine*` are the MLX affine path behind them. +const std = @import("std"); const t = @import("types.zig"); const quant = @import("core").quant; @@ -30,23 +31,33 @@ fn affineOf(proj: Projection, h: mlx.Matrix) Affine { /// matmul(x, proj) for a projection of any format: fp32 when `f32_out`, else x's kind (the MLX rules of `affine`). pub fn project(o: Ops, x: Tensor, proj: Projection, m: usize, f32_out: bool) Error!Tensor { - switch (proj.handle) { + if (proj.nvfp4) |h| return nvfp4Project(o, x, proj, h, m, f32_out); + if (proj.fp8) |h| return fp8Project(o, x, proj, h, m, f32_out); + switch (proj.handle orelse { + return error.BadShape; + }) { .mlx => |h| return affine(o, x, affineOf(proj, h), m, f32_out), .dense => |h| switch (h.dtype) { .f32 => { - if (f32_out or m == 0 or x.kind == .f32) return error.BadShape; + if (f32_out or m == 0 or x.kind == .f32) { + return error.BadShape; + } const out: Tensor = .{ .ptr = try o.arena.take(m * proj.n * x.kind.size()), .kind = x.kind }; try denseRows(o, x, h.weight, out, m, proj.n, proj.k); return out; }, .bf16 => { - if (m == 0 or x.kind != .bf16) return error.BadShape; + if (m == 0 or x.kind != .bf16) { + return error.BadShape; + } const kind: t.Kind = if (f32_out) .f32 else .bf16; const out: Tensor = .{ .ptr = try o.arena.take(m * proj.n * kind.size()), .kind = kind }; try denseGemm(o, o.l.dense.serve, x, h.weight, out, m, proj.n, proj.k); return out; }, - else => return error.BadShape, + else => { + return error.BadShape; + }, }, .bf16 => |h| { if (f32_out or m == 0 or x.kind != .bf16) return error.BadShape; @@ -63,7 +74,7 @@ pub fn project(o: Ops, x: Tensor, proj: Projection, m: usize, f32_out: bool) Err /// silu(gate) x up into `act` (m, n / 2) from an interleaved gate/up BF16 projection (n, k), in the WMMA epilogue. pub fn projectSilu(o: Ops, x: Tensor, proj: Projection, m: usize, act: Tensor) Error!void { - const h = switch (proj.handle) { + const h = switch (proj.handle orelse return error.BadShape) { .dense => |d| d, .mlx, .bf16 => return error.BadShape, }; @@ -76,7 +87,8 @@ pub fn projectSilu(o: Ops, x: Tensor, proj: Projection, m: usize, act: Tensor) E pub fn projectGroup(o: Ops, x: Tensor, ps: []const Projection, m: usize, outs: []Tensor) Error!bool { var ws: [4]Affine = undefined; if (ps.len > ws.len) return false; - for (ps, ws[0..ps.len]) |pr, *w| switch (pr.handle) { + // a decoded projection (NVFP4, FP8) has no grouped tile: false sends the caller to the plain product + for (ps, ws[0..ps.len]) |pr, *w| switch (pr.handle orelse return false) { .mlx => |h| w.* = affineOf(pr, h), .dense, .bf16 => return false, }; @@ -85,7 +97,7 @@ pub fn projectGroup(o: Ops, x: Tensor, ps: []const Projection, m: usize, outs: [ /// The routed gate and up with the activation as the epilogue; null when the format or the tile does not take it. pub fn projectRoutedAct(o: Ops, x: Tensor, proj: Projection, items: u64, count: usize, members: u64, pairs: usize, x_div: usize, rows: usize, limit: f32) Error!?Tensor { - switch (proj.handle) { + switch (proj.handle orelse return null) { .mlx => |h| return affineRoutedAct(o, x, affineOf(proj, h), items, count, members, pairs, x_div, rows, limit), .dense, .bf16 => return null, } @@ -93,7 +105,7 @@ pub fn projectRoutedAct(o: Ops, x: Tensor, proj: Projection, items: u64, count: /// `project` (fp32) then tf_nemo_relu2 into `out`, in one launch; false where another tile takes the product. pub fn projectRelu2(o: Ops, x: Tensor, proj: Projection, m: usize, out: Tensor) Error!bool { - const h = switch (proj.handle) { + const h = switch (proj.handle orelse return false) { .mlx => |h| h, .dense, .bf16 => return false, }; @@ -134,7 +146,7 @@ pub fn projectRoutedRelu2( rows: usize, out: Tensor, ) Error!bool { - const h = switch (proj.handle) { + const h = switch (proj.handle orelse return false) { .mlx => |h| h, .dense, .bf16 => return false, }; @@ -172,11 +184,11 @@ pub fn projectRoutedPlainRelu2( plain: Projection, plain_out: Tensor, ) Error!bool { - const ha = switch (routed.handle) { + const ha = switch (routed.handle orelse return false) { .mlx => |h| h, .dense, .bf16 => return false, }; - const hb = switch (plain.handle) { + const hb = switch (plain.handle orelse return false) { .mlx => |h| h, .dense, .bf16 => return false, }; @@ -223,7 +235,7 @@ pub fn projectRoutedPlainRelu2( /// matmul_routed on a stack of experts: every item in one launch; out (pairs, N) fp32. pub fn projectRouted(o: Ops, x: Tensor, proj: Projection, items: u64, count: usize, members: u64, pairs: usize, x_div: usize, rows: usize, expert_rows: usize) Error!u64 { - switch (proj.handle) { + switch (proj.handle orelse return error.BadShape) { .mlx => |h| return affineRouted(o, x, affineOf(proj, h), items, count, members, pairs, x_div, rows, expert_rows), .dense, .bf16 => return error.BadShape, } @@ -231,10 +243,11 @@ pub fn projectRouted(o: Ops, x: Tensor, proj: Projection, items: u64, count: usi /// gather_rows: `n` embedding rows of a table of any format with a row gather, by device ids, dequantized into `out`. pub fn embedRows(o: Ops, table: Projection, ids: u64, n: usize, out: Tensor) Error!void { - switch (table.handle) { + switch (table.handle orelse return error.BadShape) { .mlx => |h| return embedAffine(o, affineOf(table, h), ids, n, out), .dense => |h| try o.l.tf_embed_dense(p(h.weight), @backingInt(try kindOf(h.dtype)), @ptrFromInt(ids), int(n), int(table.k), p(out.ptr), @backingInt(out.kind), o.stream), .bf16 => |h| try o.l.tf_embed_dense(p(h.weight), @backingInt(t.Kind.bf16), @ptrFromInt(ids), int(n), int(table.k), p(out.ptr), @backingInt(out.kind), o.stream), + // ModelOpt quantizes linear modules; an embedding table is BF16 or a float table in every checkpoint it writes } } @@ -378,7 +391,6 @@ pub fn affineRouted(o: Ops, x: Tensor, w: Affine, items: u64, count: usize, memb } test "a routed prompt without its average rows per expert refuses, instead of guessing the 64-row tile" { - const std = @import("std"); var arena = @import("../arena.zig").Arena.counting(); const o: Ops = .{ .l = undefined, .bf16 = true, .stream = null, .arena = &arena, .prefill = true }; const x = Tensor{ .ptr = 0, .kind = .bf16 }; @@ -399,9 +411,13 @@ pub fn denseRows(o: Ops, x: Tensor, w: u64, out: Tensor, rows: usize, n: usize, /// x (rows, k) BF16 times BF16 weights [n, k] on `tile`: `out` fp32, or BF16 rounded once. pub fn denseGemm(o: Ops, tile: DenseTile, x: Tensor, w: u64, out: Tensor, rows: usize, n: usize, k: usize) Error!void { - if (x.kind != .bf16 or out.kind == .f16) return error.BadShape; + if (x.kind != .bf16 or out.kind == .f16) { + return error.BadShape; + } const wide = out.kind == .f32; - if (o.l.dense.refusal(tile, x.ptr, w, int(rows), int(n), int(k)) != null) return error.BadShape; + if (o.l.dense.refusal(tile, x.ptr, w, int(rows), int(n), int(k)) != null) { + return error.BadShape; + } try o.l.dense.gemm(o.l.r, tile, x.ptr, w, if (wide) out.ptr else 0, if (wide) 0 else out.ptr, int(rows), int(n), int(k), o.stream); } @@ -414,3 +430,69 @@ fn kindOf(dtype: quant.DType) Error!t.Kind { else => error.BadShape, }; } + +/// An FP8 product: the checkpoint's E4M3 codes as stored, decoded in flight and scaled once in f32. +fn fp8Project(o: Ops, x: Tensor, proj: Projection, h: quant.fp8.Matrix, m: usize, f32_out: bool) Error!Tensor { + if (m == 0 or x.kind != .bf16 or !o.bf16) { + return error.BadShape; + } + const wide: Tensor = .{ .ptr = try o.arena.take(m * proj.n * 4), .kind = .f32 }; + if (o.stream == counting) return .{ .ptr = try o.arena.take(m * proj.n * (if (f32_out) 4 else x.kind.size())), .kind = if (f32_out) .f32 else x.kind }; + const launched = @import("../launches/fp8.zig"); + const w: launched.Weight = .{ + .x = x.ptr, + .codes = h.codes, + .scale = h.scale, + .out = wide.ptr, + .m = int(m), + .n = int(proj.n), + .k = int(proj.k), + }; + launched.Kernels.gemmGo(&o.l.fp8, o.l.r, w, o.stream) catch |err| + return if (err == error.Invalid) error.BadShape else error.HipFailed; + if (f32_out) return wide; + const narrow: Tensor = .{ .ptr = try o.arena.take(m * proj.n * x.kind.size()), .kind = x.kind }; + try o.cast(wide, narrow, m * proj.n); + return narrow; +} + +/// An NVFP4 product: the checkpoint's codes and group scales as stored, e2m1 decoded in flight by one kernel. +fn nvfp4Project(o: Ops, x: Tensor, proj: Projection, h: quant.nvfp4.Matrix, m: usize, f32_out: bool) Error!Tensor { + if (m == 0 or x.kind != .bf16 or !o.bf16) { + return error.BadShape; + } + if (proj.k % 32 != 0) { + return error.BadShape; + } + const wide: Tensor = .{ .ptr = try o.arena.take(m * proj.n * 4), .kind = .f32 }; + // the counting stream sizes the arena: no product runs on its addresses, and its kind is the one stored + if (o.stream == counting) return .{ .ptr = try o.arena.take(m * proj.n * (if (f32_out) 4 else x.kind.size())), .kind = if (f32_out) .f32 else x.kind }; + const launched = @import("../launches/nvfp4.zig"); + const w: launched.Weight = .{ + .x = x.ptr, + .words = h.codes, + .scale = .{ .p = h.scale, .kind = @backingInt(h.tables) }, + .out = wide.ptr, + .m = int(m), + .n = int(proj.n), + .k = int(proj.k), + .global = h.global, + }; + // one product for every row count, so a row's bits do not depend on how many rows its round carries + launched.Kernels.gemmGo(&o.l.nvfp4, o.l.r, w, o.stream) catch |err| + return if (err == error.Invalid) error.BadShape else error.HipFailed; + if (f32_out) return wide; + const narrow: Tensor = .{ .ptr = try o.arena.take(m * proj.n * x.kind.size()), .kind = x.kind }; + try o.cast(wide, narrow, m * proj.n); + return narrow; +} + +test "a grouped product declines both ModelOpt formats" { + var arena = @import("../arena.zig").Arena.counting(); + const o: Ops = .{ .l = undefined, .bf16 = true, .stream = null, .arena = &arena }; + const x = Tensor{ .ptr = 0, .kind = .bf16 }; + const nv: Projection = .{ .n = 1024, .k = 2048, .nvfp4 = .{ .codes = 0, .scale = 0, .tables = .bf16, .global = 1 } }; + const fp: Projection = .{ .n = 1024, .k = 2048, .fp8 = .{ .codes = 0, .scale = 0 } }; + var outs: [4]Tensor = undefined; + try std.testing.expect(!(try projectGroup(o, x, &.{ nv, fp }, 1, &outs))); +} diff --git a/zig/src/hip/root.zig b/zig/src/hip/root.zig index ac6b5bd46b4..6fc91ffc7b3 100644 --- a/zig/src/hip/root.zig +++ b/zig/src/hip/root.zig @@ -44,6 +44,8 @@ pub const admission = @import("admission.zig"); pub const Device = @import("device.zig").Device; pub const Upload = @import("upload.zig").Upload; pub const quant = @import("core").quant; +pub const nvfp4 = @import("launches/nvfp4.zig"); +pub const fp8 = @import("launches/fp8.zig"); pub const registry = @import("core").registry; pub const collective = @import("collective.zig"); pub const moe = @import("moe.zig"); diff --git a/zig/tests/hip/contract_main.zig b/zig/tests/hip/contract_main.zig index a244bb06b37..444893051c7 100644 --- a/zig/tests/hip/contract_main.zig +++ b/zig/tests/hip/contract_main.zig @@ -29,6 +29,7 @@ const argmax_k = @import("contract_argmax.zig"); const pair_k = @import("contract_relu2_pair.zig"); const heads_rows_k = @import("contract_heads_rows.zig"); const dense_k = @import("contract_dense.zig"); +const nvfp4_k = @import("contract_nvfp4.zig"); const dense12_k = @import("contract_dense_wmma12.zig"); const silu_k = @import("contract_silu_fuse.zig"); const gate_k = @import("contract_moe_gate.zig"); @@ -180,6 +181,10 @@ fn run(a: std.mem.Allocator, io: std.Io) !usize { for (&moes, [_]moe_k.Which{ .relu2, .combine, .combine_f32 }) |*m, w| m.* = .init(a, &r, s, &l, w); defer for (&moes) |*m| m.deinit(); for (&moes) |*m| try kernels.append(a, m.kernel()); + var products: [2]nvfp4_k.Product = undefined; + for (&products, std.enums.values(nvfp4_k.Which)) |*p, w| p.* = .init(a, &r, s, &l, w); + defer for (&products) |*p| p.deinit(); + for (&products) |*p| try kernels.append(a, p.kernel()); var wide = wide_k.Wide.init(a, &r, s, &l); defer wide.deinit(); try kernels.append(a, wide.kernel()); diff --git a/zig/tests/hip/contract_nvfp4.zig b/zig/tests/hip/contract_nvfp4.zig new file mode 100644 index 00000000000..55a16400c26 --- /dev/null +++ b/zig/tests/hip/contract_nvfp4.zig @@ -0,0 +1,223 @@ +//! The ModelOpt products under the contract: NVFP4's e2m1 codes with a group scale, and FP8's E4M3 codes with one. +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 quant = core.quant; + +pub const Which = enum { nvfp4, fp8 }; + +/// The kernel's own chain: k fmaf into the sum, a group's fmaf into the accumulator (NVFP4), then the scale. +fn depthNv(s: c.Shape) usize { + return s.k + s.k / quant.nvfp4.group + 1; +} + +/// FP8 has no groups: k fmaf into the sum, then the scale. +fn depthFp8(s: c.Shape) usize { + return s.k + 1; +} + +const served = [_]c.Shape{ + .{ .rows = 1, .n = 256, .k = 4096 }, + .{ .rows = 7, .n = 1024, .k = 1024 }, + .{ .rows = 129, .n = 130, .k = 2048 }, +}; + +pub fn spec(w: Which) c.Spec { + return .{ + .name = switch (w) { + .nvfp4 => "hip ModelOpt NVFP4 product", + .fp8 => "hip ModelOpt FP8 product", + }, + .accum = .f32, + .depth = switch (w) { + .nvfp4 => depthNv, + .fp8 => depthFp8, + }, + .out = .f32, + .served = &served, + .tiles = .{ .{ .size = 256 }, .{}, .{} }, + }; +} + +pub const Product = struct { + rig: rig_.Rig, + l: *const hip.Launcher, + which: Which, + arena: std.heap.ArenaAllocator, + shape: c.Shape = undefined, + x: []u16 = &.{}, + codes: []u8 = &.{}, + table: []u16 = &.{}, + global: f32 = 1, + dx: u64 = 0, + dc: u64 = 0, + dt: u64 = 0, + ds: u64 = 0, + out: u64 = 0, + + pub fn init(a: std.mem.Allocator, r: *const hip.Runtime, s: hip.Stream, l: *const hip.Launcher, w: Which) Product { + return .{ .rig = .{ .a = a, .r = r, .s = s }, .l = l, .which = w, .arena = .init(a) }; + } + + pub fn deinit(t: *Product) void { + t.arena.deinit(); + t.rig.deinit(); + } + + const vt = g.hooks(Product); + + pub fn kernel(t: *Product) g.Kernel { + return .{ .spec = spec(t.which), .ctx = t, .vt = &vt }; + } + + pub fn prepare(t: *Product, s: c.Shape, fill: g.Fill, seed: u64) !bool { + if (s.rows == 0 or s.n == 0 or s.k == 0 or s.k % 32 != 0) return false; + t.rig.reset(); + _ = t.arena.reset(.retain_capacity); + const a = t.arena.allocator(); + t.shape = s; + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + t.x = try a.alloc(u16, s.rows * s.k); + for (t.x) |*v| v.* = if (fill == .stress) + c.toBf16(@as(f32, @floatFromInt(@as(i8, @intCast(rng.uintLessThan(u8, 6))) - 3)) / 2) + else + c.toBf16(rng.float(f32) * 2 - 1); + if (fill == .nonfinite and t.x.len > 0) t.x[0] = c.toBf16(std.math.inf(f32)); + t.dx = try t.rig.input(std.mem.sliceAsBytes(t.x)); + + switch (t.which) { + .nvfp4 => { + t.codes = try a.alloc(u8, s.n * s.k / 2); + // stress: e2m1's largest level in both nibbles, so an fp16 sum would round + for (t.codes) |*b| b.* = if (fill == .stress) 0x77 else @intCast(rng.uintLessThan(u16, 256)); + t.table = try a.alloc(u16, s.n * (s.k / quant.nvfp4.group)); + // E4M3 in [0.5, 1.875) widened to BF16, exactly what the reader uploads + for (t.table) |*v| { + // stress: one exact scale, so a group's product is exact too + const byte: u8 = if (fill == .stress) 0x38 else @intCast(0x30 + rng.uintLessThan(u8, 0x10)); + const scale: f32 = @floatCast(quant.fp8.e4m3(byte)); + v.* = @truncate(@as(u32, @bitCast(scale)) >> 16); + } + t.global = if (fill == .stress) 0.5 else 0.3; + t.dc = try t.rig.input(t.codes); + t.dt = try t.rig.input(std.mem.sliceAsBytes(t.table)); + const one = [_]f32{t.global}; + t.ds = try t.rig.input(std.mem.sliceAsBytes(&one)); + }, + .fp8 => { + t.codes = try a.alloc(u8, s.n * s.k); + for (t.codes) |*b| { + // stress: E4M3 values in [1, 1.875), each an exact multiple of 0.125 + var v: u8 = if (fill == .stress) @intCast(0x38 + rng.uintLessThan(u8, 8)) else @intCast(rng.uintLessThan(u16, 256)); + if (v & 0x7f == 0x7f) v &= 0xfe; // E4M3's NaN codes are refused at read + b.* = v; + } + t.global = if (fill == .stress) 0.5 else 0.01171875; + t.dc = try t.rig.input(t.codes); + const one = [_]f32{t.global}; + t.ds = try t.rig.input(std.mem.sliceAsBytes(&one)); + }, + } + t.out = try t.rig.output(s.rows * s.n * 4); + return true; + } + + pub fn run(t: *Product) !void { + const s = t.shape; + switch (t.which) { + .nvfp4 => { + const w: hip.nvfp4.Weight = .{ + .x = t.dx, + .words = t.dc, + .scale = .{ .p = t.dt, .kind = @backingInt(quant.Tables.bf16) }, + .out = t.out, + .m = @intCast(s.rows), + .n = @intCast(s.n), + .k = @intCast(s.k), + .global = t.global, + }; + try hip.nvfp4.Kernels.gemmGo(&t.l.nvfp4, t.l.r, w, t.rig.s.handle); + }, + .fp8 => { + const w: hip.fp8.Weight = .{ + .x = t.dx, + .codes = t.dc, + .scale = t.ds, + .out = t.out, + .m = @intCast(s.rows), + .n = @intCast(s.n), + .k = @intCast(s.k), + }; + try hip.fp8.Kernels.gemmGo(&t.l.fp8, t.l.r, w, t.rig.s.handle); + }, + } + try t.rig.s.synchronize(); + } + + pub fn count(t: *Product) usize { + return t.shape.rows * t.shape.n; + } + + pub fn reference(t: *Product, want: []f64, mag: []f64) !void { + const s = t.shape; + for (0..s.rows) |r| for (0..s.n) |col| { + var acc: f64 = 0; + var abs: f64 = 0; + for (0..s.k) |j| { + const code: f64 = switch (t.which) { + .nvfp4 => quant.nvfp4.e2m1(if ((j & 1) == 0) t.codes[col * (s.k / 2) + j / 2] & 0xf else t.codes[col * (s.k / 2) + j / 2] >> 4), + .fp8 => quant.fp8.e4m3(t.codes[col * s.k + j]), + }; + const scale: f64 = switch (t.which) { + .nvfp4 => @as(f64, @floatCast(@as(f32, @bitCast(@as(u32, t.table[col * (s.k / quant.nvfp4.group) + j / quant.nvfp4.group]) << 16)))) * @as(f64, t.global), + .fp8 => @as(f64, t.global), + }; + const term = c.fromBf16(t.x[r * s.k + j]) * code * scale; + acc += term; + abs += @abs(term); + } + want[r * s.n + col] = acc; + mag[r * s.n + col] = abs; + }; + } + + /// The same sums in an accumulator, for gate 4: the kernel's k-long chain, terms scaled as the reference has them. + pub fn simulate(t: *Product, acc: c.Accum, order: g.Order, out: []f64) !void { + _ = order; // the kernel sums one chain in k order + const s = t.shape; + for (0..s.rows) |r| { + for (0..s.n) |col| { + var exact: f64 = 0; + var a: f32 = 0; + for (0..s.k) |j| { + const code: f64 = switch (t.which) { + .nvfp4 => quant.nvfp4.e2m1(if ((j & 1) == 0) t.codes[col * (s.k / 2) + j / 2] & 0xf else t.codes[col * (s.k / 2) + j / 2] >> 4), + .fp8 => quant.fp8.e4m3(t.codes[col * s.k + j]), + }; + const scale: f64 = switch (t.which) { + .nvfp4 => @as(f64, @floatCast(@as(f32, @bitCast(@as(u32, t.table[col * (s.k / quant.nvfp4.group) + j / quant.nvfp4.group]) << 16)))) * @as(f64, t.global), + .fp8 => @as(f64, t.global), + }; + const term = c.fromBf16(t.x[r * s.k + j]) * code * scale; + switch (acc) { + // exact fp32 sums: no intermediate rounding, one store; fp16 and bf16 round each step + .f32 => exact += term, + .bf16 => a = @floatCast(core.bf16_round.bf16(@as(f64, a) + term)), + .f16 => a = @floatCast(@as(f16, @floatCast(@as(f64, a) + term))), + .none => unreachable, + } + } + out[r * s.n + col] = switch (acc) { + .f32 => exact, + else => @floatCast(a), + }; + } + } + } +}; diff --git a/zig/tests/qwen35/main.zig b/zig/tests/qwen35/main.zig index 01d16395fbf..4b493fcb48e 100644 --- a/zig/tests/qwen35/main.zig +++ b/zig/tests/qwen35/main.zig @@ -148,14 +148,23 @@ const Check = struct { buffers: usize = 0, bytes: usize = 0, - /// Reads `b` back and compares dtype, shape and bytes with the host tensor. - fn buf(c: *Check, b: Buf, t: Tensor) !void { - if (b.dtype != t.dtype or b.rank != t.rank or !std.mem.eql(u8, std.mem.sliceAsBytes(&b.shape), std.mem.sliceAsBytes(&t.shape)) or b.len != t.bytes.len) return error.ShapeMismatch; + /// Reads `b` back and compares dtype, shape and bytes with the host tensor; a bare `[]const f32` is a scale. + fn buf(c: *Check, b: Buf, t: anytype) !void { + const bytes = switch (@typeInfo(@TypeOf(t))) { + .@"struct" => blk: { + if (@TypeOf(t) != Tensor) @compileError("a host buffer is a tensor or a number slice, found " ++ @typeName(@TypeOf(t))); + if (b.dtype != t.dtype or b.rank != t.rank or !std.mem.eql(u8, std.mem.sliceAsBytes(&b.shape), std.mem.sliceAsBytes(&t.shape)) or b.len != t.bytes.len) return error.ShapeMismatch; + break :blk t.bytes; + }, + .pointer => std.mem.sliceAsBytes(t), + else => @compileError("a host buffer is a tensor or a number slice, found " ++ @typeName(@TypeOf(t))), + }; + if (b.len != bytes.len) return error.ShapeMismatch; const got = try c.gpa.alloc(u8, b.len); defer c.gpa.free(got); const device: hip.DeviceBuffer = .{ .r = c.driver, .ptr = @ptrFromInt(b.ptr), .len = b.len }; try device.download(0, got); - if (!std.mem.eql(u8, got, t.bytes)) return error.BytesDiffer; + if (!std.mem.eql(u8, got, bytes)) return error.BytesDiffer; c.buffers += 1; c.bytes += b.len; } @@ -166,7 +175,11 @@ const Check = struct { switch (@typeInfo(T)) { .@"struct" => if (T == Buf) try c.buf(dev, h) else inline for (@typeInfo(T).@"struct".field_names) |name| try c.walk(@field(dev, name), if (@hasField(@TypeOf(h), name)) @field(h, name) else {}), .@"union" => switch (dev) { - inline else => |payload, tag| try c.walk(payload, @field(h, @tagName(tag))), + inline else => |payload, tag| { + if (comptime @hasField(@TypeOf(h), @tagName(tag))) try c.walk(payload, @field(h, @tagName(tag))) else if (comptime std.mem.eql(u8, @tagName(tag), "core")) { + try c.walk(payload, h); + } else return error.TagMismatch; + }, }, .optional => if (dev) |d| try c.walk(d, h.?) else if (h != null) return error.ShapeMismatch, else => {},