Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
1 change: 1 addition & 0 deletions build.zig
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
25 changes: 25 additions & 0 deletions docs/quantization.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
1 change: 1 addition & 0 deletions zig/build/checkpoint_io_host.zig
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
}
26 changes: 13 additions & 13 deletions zig/build/hip.zig
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down Expand Up @@ -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});
Expand Down Expand Up @@ -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<Dot, 6, 1, 8> 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);
Expand Down
85 changes: 85 additions & 0 deletions zig/build/hip_headers.zig
Original file line number Diff line number Diff line change
@@ -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 <hip/hip_runtime.h>\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]);
}
153 changes: 153 additions & 0 deletions zig/kernels/hip/quant/fp8_tiles.hpp
Original file line number Diff line number Diff line change
@@ -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 <hip/hip_bfloat16.h>
#include <hip/hip_runtime.h>

#include <cstdint>

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<float>(m) * 0.125f * __uint_as_float((127u - 6u) << 23)
: (1.0f + static_cast<float>(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<const unsigned char*>(a.codes);
const hip_bfloat16* x = static_cast<const hip_bfloat16*>(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<long long>(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<long long>(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<float>(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<long long>(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<const unsigned char*>(a.codes);
const hip_bfloat16* x = static_cast<const hip_bfloat16*>(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<long long>(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<long long>(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<float>(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<long long>(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);
}
Loading
Loading