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

- CUDA TFQ3 (3/4/5-bit 2D-AffineCoset + randomized 2D FWHT-128) runtime and speculative drafters across Qwen3.8-27B (`qwen3_5`: pure BF16 or MLX base + `DFlash2` and `DSpine`), GLM-5.3-Flash (`glm`: `nonmoe.tffpw` + routed `layer_03..44.tffpw` + shared TFQ3 `DraftHead` for `MTP` and `DFlash2`), and Qwen3.8-Flash-Next (`flashnext`: routed `layer_00..47.tffpw` + `mtp_00.tffpw` + MLX 8-bit/32 non-MoE and 3/4/8-bit PLE), using shared `qmm_frag` `m16n8k16` split-K=8 dense kernels for bit-exact speculative verification (`rows = 1..32`) and `BM=64, BN=128` Tensor Core prefill kernels (`rows >= 48`); non-TFQ3 checkpoints keep `main`'s paths unchanged (#4986).

- CUDA kernels: GLM's mHC pre side (`tf_glm_hc_partial`, `tf_glm_hc_partial8`, `tf_glm_hc_finish` and `tf_glm_hc_finish_f32w`) takes its bodies from the new `common/mhc.cuh`, whose finish takes the mix's RMS step from its caller, so another family can instantiate them with its own; GLM keeps its entries, widths and factors, and every `glm_glue` function's SASS is unchanged at sm_80, 86, 89, 120 and 121 (#5164, refs #4926).

- CUDA: a sparse gather attention kernel over listed cache rows, with duplicate, empty and masked-index handling and contract tests, for Kolibri 1.1 (not yet wired into serving) (#5166). Thanks to @jschmied.
Expand Down
17 changes: 17 additions & 0 deletions zig/build/cuda.zig
Original file line number Diff line number Diff line change
Expand Up @@ -150,6 +150,12 @@ pub fn targets(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.bu
@import("living_dense.zig").target(b, target, optimize, cuda, mods.qwen35);
flashnextChecks(b, target, optimize, cuda, mods.core, mods.lanes, mods.qwen_vision, mods.api, opts);
b.step("compile-cuda-tests", "Compile CUDA runner without executing a GPU").dependOn(&runner_exe.step);
const tfq3_run = b.addRunArtifact(runner_exe);
tfq3_run.addArg("tfq3-contract");
b.step("tfq3-contract", "TFQ3 serial rows equal every decode and prefill width").dependOn(&tfq3_run.step);
const tfq3_limits = b.addRunArtifact(runner_exe);
tfq3_limits.addArgs(&.{ "kernel-contract", "tfq3" });
b.step("tfq3-contract-limits", "TFQ3 launch resources against the compiled CUDA images").dependOn(&tfq3_limits.step);
const startup = b.addObject(.{ .name = "modelopt-startup", .root_module = b.createModule(.{ .root_source_file = b.path("zig/modelopt_startup_compile.zig"), .target = target, .optimize = optimize, .link_libc = true, .imports = &.{.{ .name = "native", .module = native.engines }} }) });
_ = startup.getEmittedBin();
b.step("compile-modelopt-startup", "Compile actual native startup with test-only absent GPU images").dependOn(&startup.step);
Expand Down Expand Up @@ -249,9 +255,20 @@ pub fn hostTests(b: *std.Build, draft_ids: *std.Build.Module, build_options: *st
b.step("test-gradient-host", "Gradient bounds through real wrappers with recorded CUDA launches").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = cuda, .filters = &.{"train launch bounds:"} })).step);
b.step("test-tp-id-host", "Bounded NCCL-ID TP fanout and independent wire controls without devices").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = cuda, .filters = &.{"tp id coverage:"} })).step);
@import("cuda_readback_host.zig").tests(b, cuda, step);
b.step("test-cuda-tfq3-host", "CUDA TFQ3 resource ownership and format refusals without devices").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = cuda, .filters = &.{"CUDA TFQ3:"} })).step);
const runtime_host = b.step("test-runtime-host", "Shared CUDA runtime and graph host regressions");
runtime_host.dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = cuda })).step);
const mods = family(b, host, .ReleaseSafe, cuda, draft_ids);
const tfq3_host = b.createModule(.{
.root_source_file = b.path("zig/cuda_tfq3_host.zig"),
.target = host,
.link_libc = true,
.imports = &.{ .{ .name = "cuda", .module = cuda }, .{ .name = "qwen35", .module = mods.qwen35 } },
});
b.top_level_steps.get("test-cuda-tfq3-host").?.step.dependOn(&b.addRunArtifact(b.addTest(.{
.root_module = tfq3_host,
.filters = &.{"CUDA TFQ3 host:"},
})).step);
@import("cuda_checkpoint_cache_host.zig").steps(b, step);
b.step("test-lfm2-load-host", "LFM2 decision model metadata and load ownership without a GPU").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = lfm2Module(b, host, .debug, cuda, mods.core) })).step);
engines_build.qwen3HostTest(b, engines_build.qwen3Module(b, host, .debug, cuda, mods.core, mods.lanes, mods.api), step);
Expand Down
4 changes: 4 additions & 0 deletions zig/build/cuda_kernels.zig
Original file line number Diff line number Diff line change
Expand Up @@ -183,6 +183,10 @@ pub const kernels = [_]Kernel{
.{ .name = "exl3_linear", .flags = &.{ "-O3", "--expt-relaxed-constexpr" } }, // exl3/linear.cu's device code, tensorfold_exl3_linear_v5
.{ .name = "exl3_experts", .flags = &.{ "-O3", "--expt-relaxed-constexpr" } }, // exl3/experts.cu's device code, tensorfold_exl3_experts
.{ .name = "exl3_candidate", .flags = &.{ "-O3", "--fmad=false", "--ftz=false" } }, // #806's EXL3 tiles: Dense's candidate
// TFQ3 dense 3/4/5-bit 2D-AffineCoset + FWHT-128.
.{ .name = "tfq3", .flags = &.{ "-O3", "--use_fast_math" }, .min_sm = 80 },
// TFQ3 routed MoE 3/4/5-bit HeatAlloc kernels.
.{ .name = "tfq3_moe", .flags = &.{ "-O3", "--use_fast_math" }, .min_sm = 80 },
.{ .name = "glm_vision", .flags = &.{"-O3"} }, // ours: GLM's image tower steps around cuBLASLt (norms, rotary, softmax, merger)
.{ .name = "glm_mm", .flags = &.{"-O3"} }, // ours: GLM's bf16 linears on tensor cores, weights tiled at load, row-stable
.{ .name = "glm_dflash", .flags = &.{"-O3"} }, // the DFlash2 block drafter
Expand Down
141 changes: 141 additions & 0 deletions zig/cuda_tfq3_host.zig
Original file line number Diff line number Diff line change
@@ -0,0 +1,141 @@
//! CUDA TFQ3 host regressions: format identity, lifecycle failures and checkpoint arithmetic.
const std = @import("std");
const cuda = @import("cuda");
const fmt = cuda.tfq3_format;
const t = std.testing;

fn bf16(x: f32) f32 {
const u: u32 = @bitCast(x);
return @bitCast((u + 0x7fff + ((u >> 16) & 1)) & 0xffff0000);
}

test "CUDA TFQ3 host: routed SiLU has its BF16 point before multiplication" {
const sl: f32 = 0.5 / (1 + @exp(@as(f32, -0.5)));
const want = bf16(bf16(sl) * 1.5);
try t.expectEqual(@as(f32, 0.46484375), want);
try t.expect(bf16(sl * 1.5) != want);
const source = @embedFile("kernels/cuda/tfq3_common.cuh");
try t.expect(std.mem.indexOf(u8, source, "if (act_mode != 0u) sg =") == null);
try t.expect(std.mem.indexOf(u8, source, "sg = __bfloat162float(__float2bfloat16(sg));") != null);
}

fn moeShard() ![]u8 {
const bytes = try t.allocator.alloc(u8, 4 * fmt.section_align);
@memset(bytes, 0);
const words = fmt.tensorWords(128, 128, 4);
const h: fmt.TfpwHeader = .{
.magic = fmt.magic_tfpw,
.version = 3,
.layer_idx = 0,
.num_experts = 1,
.num_tensors = 3,
.hidden_size = 128,
.moe_inter = 128,
.reserved0 = 0,
.raw_fp8_bytes = 0,
.stream_words = 3 * words,
.scale_halfs = 3,
.off_meta = 144,
.off_scales = fmt.section_align,
.off_weights = 2 * fmt.section_align,
.reserved1 = @splat(0),
.meta_tag = @splat(0),
};
@memcpy(bytes[0..144], std.mem.asBytes(&h));
var m = std.mem.zeroes(fmt.TfpwExpertMeta);
m.b_bits = 4;
m.up_word_off = words;
m.down_word_off = 2 * words;
m.up_sc_off = 1;
m.down_sc_off = 2;
@memcpy(bytes[144..208], std.mem.asBytes(&m));
return bytes;
}

test "CUDA TFQ3 host: decoder layer identity is checked, MTP is unconstrained" {
const bytes = try moeShard();
defer t.allocator.free(bytes);
_ = try fmt.validateTfpw(bytes, 1, 128, 128, 0);
try t.expectError(error.Tfq3LayerMismatch, fmt.validateTfpw(bytes, 1, 128, 128, 1));
_ = try fmt.validateTfpw(bytes, 1, 128, 128, null);
}

fn enumerate(gpa: std.mem.Allocator, dir: []const u8) !void {
const paths = try fmt.listShards(gpa, t.io, dir, "");
defer fmt.freePaths(gpa, paths);
try t.expectEqual(@as(usize, 2), paths.len);
try t.expectEqualStrings("a.tffpw", std.fs.path.basename(paths[0]));
try t.expectEqualStrings("b.tffpw", std.fs.path.basename(paths[1]));
}

test "CUDA TFQ3 host: shard enumeration owns every joined path on allocation failure" {
var tmp = t.tmpDir(.{});
defer tmp.cleanup();
const dir = try tmp.dir.realPathFileAlloc(t.io, ".", t.allocator);
defer t.allocator.free(dir);
try tmp.dir.writeFile(t.io, .{ .sub_path = "b.tffpw", .data = "b" });
try tmp.dir.writeFile(t.io, .{ .sub_path = "a.tffpw", .data = "a" });
try tmp.dir.writeFile(t.io, .{ .sub_path = "ignored.bin", .data = "x" });
try t.checkAllAllocationFailures(t.allocator, enumerate, .{dir});
}

test "CUDA TFQ3 host: Geometry.read keeps an MLX checkpoint with orphan tables" {
const config =
\\{"model_type":"qwen3_5","quantization":{"group_size":64,"bits":4,"mode":"affine"},"tie_word_embeddings":false,
\\ "text_config":{"model_type":"qwen3_5_text","attention_bias":false,"attn_output_gate":true,"hidden_act":"silu",
\\ "head_dim":256,"linear_key_head_dim":128,"linear_value_head_dim":128,"linear_conv_kernel_dim":4,
\\ "hidden_size":5120,"intermediate_size":17408,"num_hidden_layers":4,"vocab_size":248320,"linear_num_key_heads":16,
\\ "linear_num_value_heads":48,"num_attention_heads":24,"num_key_value_heads":4,"rms_norm_eps":1e-06,
\\ "max_position_embeddings":262144,"tie_word_embeddings":false,
\\ "layer_types":["linear_attention","linear_attention","linear_attention","full_attention"],
\\ "rope_parameters":{"rope_type":"default","rope_theta":10000000,"partial_rotary_factor":0.25}}}
;
var tmp = t.tmpDir(.{});
defer tmp.cleanup();
const dir = try tmp.dir.realPathFileAlloc(t.io, ".", t.allocator);
defer t.allocator.free(dir);
try tmp.dir.writeFile(t.io, .{ .sub_path = "config.json", .data = config });
const Geometry = @import("qwen35").geometry.Geometry;
const before = try Geometry.read(t.allocator, t.io, dir);
var tables: [fmt.tables_file_bytes]u8 = @splat(0);
std.mem.writeInt(u32, tables[0..4], fmt.magic_tables, .little);
std.mem.writeInt(u32, tables[4..8], 3, .little);
try tmp.dir.writeFile(t.io, .{ .sub_path = "pw_v3_tables.bin", .data = &tables });
const after = try Geometry.read(t.allocator, t.io, dir);
try t.expect(!after.tfq3);
try t.expectEqualDeep(before, after);
}

test "CUDA TFQ3 host: output sign periods repeat through narrowed tail views" {
const base: cuda.tfq3.DenseWeight = .{
.words = 0,
.scales = 0,
.tables = 0,
.n = 248320,
.k = 128,
.bits = 4,
.sr_split = 8192,
};
const tail = try base.sliceRows(247936, 384);
try t.expectEqual(@as(u32, 8192), tail.sr_split);
try t.expectEqual(@as(u32, 247936), tail.row_off);
for ([_]u32{ 2047, 2048, 8191, 8192, 16383, 16384, 247936 }) |row| {
const period: u32 = 8192;
const local = row % period;
if (row >= 2 * period) try t.expect(row - period != local);
}
const source = @embedFile("kernels/cuda/tfq3_common.cuh");
try t.expect(std.mem.indexOf(u8, source, "r0 % sr_split") != null);
}

test "CUDA TFQ3 host: standalone heads keep absolute signs across large row boundaries" {
const head: cuda.tfq3.DenseWeight = .{ .words = 0, .scales = 0, .tables = 0, .n = 154880, .k = 4096, .bits = 4 };
try t.expectEqual(@as(u32, 0), head.sr_split);
for ([_]u32{ 8192, 16384, 154496 }) |row| {
const view = try head.sliceRows(row, 128);
try t.expectEqual(row, view.row_off);
try t.expectEqual(@as(u32, 0), view.sr_split);
}
const source = @embedFile("kernels/cuda/tfq3_common.cuh");
try t.expect(std.mem.indexOf(u8, source, "sr_split != 0u ? (r0 % sr_split) : r0") != null);
}
Loading
Loading