From ba178b405b6d72feda267f540ff0b5f126fc2966 Mon Sep 17 00:00:00 2001 From: Shinto C V <11365900+cshintov@users.noreply.github.com> Date: Fri, 6 Nov 2026 08:11:30 +0530 Subject: [PATCH 01/13] qwen27: Qwen3.6-35B-A3B on #1125's routed path, 16 query heads over 2 on main's attention Geometry --- zig/src/families/qwen27/attention_plan.zig | 9 +++-- zig/src/families/qwen27/config_test.zig | 22 ++++++++++++ zig/src/families/qwen27/model.zig | 14 +++++++- zig/src/families/qwen27/widths.zig | 39 ++++++++++++++++++++++ 4 files changed, 81 insertions(+), 3 deletions(-) diff --git a/zig/src/families/qwen27/attention_plan.zig b/zig/src/families/qwen27/attention_plan.zig index 870c888d159..a7f1b39451e 100644 --- a/zig/src/families/qwen27/attention_plan.zig +++ b/zig/src/families/qwen27/attention_plan.zig @@ -48,9 +48,9 @@ pub const Geometry = struct { } pub fn check(g: Geometry) !void { - // The GQA group is a shader constant: 6 (24/4, 12/2 on a rank), or on one Mac 16 (32/2) or the 9B's 4 (16/4). + // The GQA group is a shader constant: 6 (24/4, 12/2 on a rank), or on one Mac 16 (32/2), 4 (16/4) or 8 (16/2). if (g.dim != 256 or g.rotary != 64 or g.heads == 0 or g.kv_heads == 0 or g.heads % g.kv_heads != 0) return error.TargetAttentionShape; - const one_mac = (g.heads == 32 and g.kv_heads == 2) or (g.heads == 16 and g.kv_heads == 4); + const one_mac = (g.heads == 32 and g.kv_heads == 2) or (g.heads == 16 and g.kv_heads == 4) or (g.heads == 16 and g.kv_heads == 2); if (g.heads / g.kv_heads != 6 and !one_mac) return error.TargetAttentionShape; } pub fn promptRows(g: Geometry, requested: u32) u32 { @@ -553,6 +553,11 @@ test "target attention reads every config dimension without widening kernel qual c.heads = 16; // its rank of a two-way split is not qualified c.kv_heads = 1; try std.testing.expectError(error.TargetAttentionShape, Geometry.fromConfig(c, true)); + c.kv_heads = 2; // Qwen3.6-35B-A3B: GQA8, one Mac only + try std.testing.expectEqual(@as(u32, 8), (try Geometry.fromConfig(c, true)).group()); + c.heads = 8; // its rank of a two-way split is not qualified + c.kv_heads = 1; + try std.testing.expectError(error.TargetAttentionShape, Geometry.fromConfig(c, true)); c.heads = 24; c.kv_heads = 2; try std.testing.expectError(error.TargetAttentionShape, Geometry.fromConfig(c, true)); diff --git a/zig/src/families/qwen27/config_test.zig b/zig/src/families/qwen27/config_test.zig index b52e086d6bf..f8560d7e1bb 100644 --- a/zig/src/families/qwen27/config_test.zig +++ b/zig/src/families/qwen27/config_test.zig @@ -146,6 +146,28 @@ test "qwen27: generation_config.json adds <|im_end|> to an HF-layout config's en try std.testing.expectEqualSlices(u32, &.{ 248044, 248046 }, shared); } +/// mlx-community/Qwen3.6-35B-A3B-4bit's text_config (its MTP and vision fields left out): no intermediate_size. +pub const a3b_json = + \\{"model_type":"qwen3_5_moe","text_config":{"model_type":"qwen3_5_moe_text","hidden_size":2048, + \\"moe_intermediate_size":512,"shared_expert_intermediate_size":512,"num_experts":256,"num_experts_per_tok":8, + \\"num_hidden_layers":40,"num_attention_heads":16,"num_key_value_heads":2,"head_dim":256,"vocab_size":248320, + \\"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,"partial_rotary_factor":0.25,"attn_output_gate":true,"eos_token_id":248044}} +; + +test "Qwen3.6-35B-A3B's config reads as routed experts of 512 over 2,048, the shared expert's width as the layer's" { + const c = try parse(std.testing.allocator, a3b_json, null); + try std.testing.expect(c.moe()); + try std.testing.expectEqual(@as(usize, 2048), c.hidden); + try std.testing.expectEqual(@as(usize, 512), c.intermediate); + try std.testing.expectEqual(@as(usize, 512), c.moe_intermediate); + try std.testing.expectEqual(@as(usize, 8), c.top_k); + try std.testing.expectEqual(@as(usize, 32), c.v_heads); + try std.testing.expect(c.renorm); // absent: renormalized + try std.testing.expectEqual(Kind.attention, c.kind(39)); + try std.testing.expectEqual(Kind.linear, c.kind(38)); +} + test "a routed config refuses a rank split" { var c = model27(); c.experts = 256; diff --git a/zig/src/families/qwen27/model.zig b/zig/src/families/qwen27/model.zig index 793e4dcb325..8c056376a86 100644 --- a/zig/src/families/qwen27/model.zig +++ b/zig/src/families/qwen27/model.zig @@ -261,7 +261,9 @@ pub fn supported(c: cfg.Config) !void { const dense = qualifiedSize(c) and c.kv_heads == 4 and c.k_heads == 16 and !c.moe(); // Ornith-1.5-122B: 256 experts of 1,024 and a shared expert of 1,024 over 3,072, 32 heads over 2 of 256 const routed = c.hidden == 3072 and c.intermediate == 1024 and c.layers == 48 and c.heads == 32 and c.kv_heads == 2 and c.k_heads == 16 and c.v_heads == 64 and c.experts == 256 and c.top_k == 8 and c.moe_intermediate == 1024; - if (!(dense or routed) or c.vocab != 248320) return error.UnqualifiedQwenShape; + // Qwen3.6-35B-A3B: 256 experts of 512 and a shared expert of 512 over 2,048, 16 heads over 2 of 256 + const a3b = c.hidden == 2048 and c.intermediate == 512 and c.layers == 40 and c.heads == 16 and c.kv_heads == 2 and c.k_heads == 16 and c.v_heads == 32 and c.experts == 256 and c.top_k == 8 and c.moe_intermediate == 512; + if (!(dense or routed or a3b) or c.vocab != 248320) return error.UnqualifiedQwenShape; try @import("geometry.zig").supported(c); } @@ -269,6 +271,16 @@ fn qualifiedGeneration(generation: u32) bool { return generation >= 13 and generation <= 18; } +test "the qualified shapes: the dense 27B, Ornith-1.5-122B and Qwen3.6-35B-A3B; a 35B of other widths is refused" { + var c = try cfg.parse(std.testing.allocator, @import("config_test.zig").a3b_json, null); + try supported(c); + c.moe_intermediate = 1024; + try std.testing.expectError(error.UnqualifiedQwenShape, supported(c)); + c.moe_intermediate = 512; + c.top_k = 10; + try std.testing.expectError(error.UnqualifiedQwenShape, supported(c)); +} + test "unknown and older GPU generations refuse before any weight load" { try std.testing.expect(qualifiedGeneration(13)); try std.testing.expect(qualifiedGeneration(15)); diff --git a/zig/src/families/qwen27/widths.zig b/zig/src/families/qwen27/widths.zig index bf27a110d42..94c8b90f977 100644 --- a/zig/src/families/qwen27/widths.zig +++ b/zig/src/families/qwen27/widths.zig @@ -279,6 +279,25 @@ fn testAdmitRouted(quantization: []const u8, why: *Why) !void { return admit(&w, c, .{ .tensor_units = true, .row_bits = &all_rows }, why); } +/// Qwen3.6-35B-A3B's shapes (no intermediate_size) at `quantization`, on a chip with or without tensor units. +fn testAdmitA3b(quantization: []const u8, units: bool, why: *Why) !void { + const a = std.testing.allocator; + const text = try std.fmt.allocPrint(a, + \\{{"model_type":"qwen3_5_moe","text_config":{{"model_type":"qwen3_5_moe_text","hidden_size":2048, + \\"moe_intermediate_size":512,"shared_expert_intermediate_size":512,"num_experts":256,"num_experts_per_tok":8, + \\"num_hidden_layers":40,"num_attention_heads":16,"num_key_value_heads":2,"head_dim":256,"vocab_size":248320, + \\"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,"partial_rotary_factor":0.25,"eos_token_id":248044}},"quantization":{s}}} + , .{quantization}); + defer a.free(text); + const c = try cfg.parse(a, text, null); + var f = try affine.Formats.init(a, text); + defer f.deinit(); + var w = try Widths.resolve(a, &f, c); + defer w.deinit(); + return admit(&w, c, .{ .tensor_units = units, .row_bits = &all_rows }, why); +} + /// TensorFold/Qwen3.8-27B-oQ4 override shapes: 4-bit g64, 5-bit GDN, MLP and attention members, one 6-bit v. const oq4 = \\{"group_size":64,"bits":4,"mode":"affine", @@ -419,3 +438,23 @@ test "a shared expert whose width differs from the experts' is refused at admiss try std.testing.expectEqual(error.SharedExpertWidth, why.reason); try std.testing.expectEqualStrings("mlp.shared_expert.down_proj", why.module); } + +test "Qwen3.6-35B-A3B's published widths are admitted with and without tensor units" { + var why: Why = .{}; + // mlx-community/Qwen3.6-35B-A3B-4bit: 4-bit g64, every layer's router and shared gate at 8 bits + const published = + \\{"group_size":64,"bits":4,"mode":"affine", + \\"language_model.model.layers.0.mlp.gate":{"group_size":64,"bits":8}, + \\"language_model.model.layers.0.mlp.shared_expert_gate":{"group_size":64,"bits":8}, + \\"language_model.model.layers.39.mlp.gate":{"group_size":64,"bits":8}, + \\"language_model.model.layers.39.mlp.shared_expert_gate":{"group_size":64,"bits":8}} + ; + for ([_]bool{ true, false }) |units| try testAdmitA3b(published, units, &why); + // a router at 8 bits with its shared gate left at 4 cannot share one matrix + const split_gate = + \\{"group_size":64,"bits":4,"mode":"affine", + \\"language_model.model.layers.0.mlp.gate":{"group_size":64,"bits":8}} + ; + try std.testing.expectError(error.UnqualifiedQwenFormat, testAdmitA3b(split_gate, false, &why)); + try std.testing.expectEqual(error.SharedGateWidth, why.reason); +} From 2b6afad27bf62ab9786f050b2164c0df0a6e5362 Mon Sep 17 00:00:00 2001 From: Shinto C V <11365900+cshintov@users.noreply.github.com> Date: Fri, 6 Nov 2026 08:12:16 +0530 Subject: [PATCH 02/13] contract: the routed block's kernels at Qwen3.6-35B-A3B's served widths (512 experts' rows over 2,048) --- zig/tests/contract/metal_affine_gather.zig | 5 +++-- zig/tests/contract/metal_qwen27_moe.zig | 4 ++-- zig/tests/contract/metal_qwen27_moe_rows.zig | 9 ++++++--- 3 files changed, 11 insertions(+), 7 deletions(-) diff --git a/zig/tests/contract/metal_affine_gather.zig b/zig/tests/contract/metal_affine_gather.zig index 91273746ce8..1f6d41ec164 100644 --- a/zig/tests/contract/metal_affine_gather.zig +++ b/zig/tests/contract/metal_affine_gather.zig @@ -76,8 +76,9 @@ const offset_inf = c.Known{ .gate = .nonfinite, .finding = "an infinite input gi pub fn spec(v: Variant) c.Spec { const known = if (v.bits == 4 and v.mutation == .none and !v.glm_m3_fast) offset_inf else null; - // Ornith-1.5-122B: gate and up 1024 x 3072, down 3072 x 1024; 32 rows an expert (32-row tiles), past 64 (64-row) - const served = &[_]c.Shape{ .{ .rows = 256, .n = 1024, .k = 3072 }, .{ .rows = 520, .n = 3072, .k = 1024 } }; + // Ornith-1.5-122B: gate and up 1024 x 3072, down 3072 x 1024; 32 rows an expert (32-row tiles), past 64 (64-row); + // Qwen3.6-35B-A3B: gate and up 512 x 2048, down 2048 x 512 + const served = &[_]c.Shape{ .{ .rows = 256, .n = 1024, .k = 3072 }, .{ .rows = 520, .n = 3072, .k = 1024 }, .{ .rows = 256, .n = 512, .k = 2048 }, .{ .rows = 520, .n = 2048, .k = 512 } }; return .{ .name = name(v), .accum = .f32, .depth = groupDepth64, .out = .bf16, .known = known, .replaces = if (v.identity) "the frozen affine_mm before exact-nonfinite groups" else null, .tiles = .{ .{ .size = 32 }, .{ .size = 64, .step = 64, .min = 64 }, .{ .size = 128, .step = 64, .min = 64 } }, .served = served }; } diff --git a/zig/tests/contract/metal_qwen27_moe.zig b/zig/tests/contract/metal_qwen27_moe.zig index 895c7dba3b4..6fb2f035680 100644 --- a/zig/tests/contract/metal_qwen27_moe.zig +++ b/zig/tests/contract/metal_qwen27_moe.zig @@ -78,8 +78,8 @@ pub const Extra = struct { .depth = rowDepth, .out = .bf16, .tiles = .{ .{ .size = 2 }, .{ .size = 8, .step = 8, .min = 8 }, .{ .size = 512, .step = 64, .min = 64 } }, - // Ornith's decode windows: gate and up (1,024 over 3,072), down (3,072 over 1,024) - .served = &.{ .{ .rows = 16, .n = 1024, .k = 3072 }, .{ .rows = 1, .n = 3072, .k = 1024 } }, + // Ornith's decode windows: gate and up (1,024 over 3,072), down (3,072 over 1,024); the 35B-A3B's (512 over 2,048) + .served = &.{ .{ .rows = 16, .n = 1024, .k = 3072 }, .{ .rows = 1, .n = 3072, .k = 1024 }, .{ .rows = 16, .n = 512, .k = 2048 }, .{ .rows = 1, .n = 2048, .k = 512 } }, }; } diff --git a/zig/tests/contract/metal_qwen27_moe_rows.zig b/zig/tests/contract/metal_qwen27_moe_rows.zig index ab460e0f0ae..c2487e5e572 100644 --- a/zig/tests/contract/metal_qwen27_moe_rows.zig +++ b/zig/tests/contract/metal_qwen27_moe_rows.zig @@ -174,7 +174,8 @@ pub const Gather = struct { .out = .raw, .nan = .{ .stated = "each sorted slot's row is its token's input row, bit for bit" }, .tiles = .{ .{ .size = 8, .step = 8, .min = 8 }, .{ .size = 256, .step = 64, .min = 64 }, .{} }, - .served = &.{ .{ .rows = 8192, .n = 3072, .k = 1 }, .{ .rows = 128, .n = 3072, .k = 1 }, .{ .rows = 8, .n = 3072, .k = 1 } }, + // Ornith's hidden width, then the 35B-A3B's + .served = &.{ .{ .rows = 8192, .n = 3072, .k = 1 }, .{ .rows = 128, .n = 3072, .k = 1 }, .{ .rows = 8, .n = 3072, .k = 1 }, .{ .rows = 8192, .n = 2048, .k = 1 }, .{ .rows = 8, .n = 2048, .k = 1 } }, }; } @@ -266,7 +267,8 @@ pub const Glu = struct { .ops = 12, .out = .bf16, .tiles = .{ .{ .size = 1 }, .{ .size = 256, .step = 1, .min = 1 }, .{} }, - .served = &.{ .{ .rows = 9216, .n = 1024, .k = 1 }, .{ .rows = 144, .n = 1024, .k = 1 }, .{ .rows = 9, .n = 1024, .k = 1 } }, + // Ornith's experts' width, then the 35B-A3B's + .served = &.{ .{ .rows = 9216, .n = 1024, .k = 1 }, .{ .rows = 144, .n = 1024, .k = 1 }, .{ .rows = 9, .n = 1024, .k = 1 }, .{ .rows = 9216, .n = 512, .k = 1 }, .{ .rows = 9, .n = 512, .k = 1 } }, }; } @@ -364,7 +366,8 @@ pub const Combine = struct { .out = .bf16, .in_place = in_out, .tiles = .{ .{ .size = 1 }, .{ .size = 256, .step = 1, .min = 1 }, .{} }, - .served = &.{ .{ .rows = 16, .n = 3072, .k = route_topk }, .{ .rows = 1, .n = 3072, .k = route_topk }, .{ .rows = 1024, .n = 3072, .k = route_topk } }, + // Ornith's hidden width, then the 35B-A3B's + .served = &.{ .{ .rows = 16, .n = 3072, .k = route_topk }, .{ .rows = 1, .n = 3072, .k = route_topk }, .{ .rows = 1024, .n = 3072, .k = route_topk }, .{ .rows = 16, .n = 2048, .k = route_topk }, .{ .rows = 1024, .n = 2048, .k = route_topk } }, }; } From 6ae514599254005581f9ed76f53d4e6ad7521ddb Mon Sep 17 00:00:00 2001 From: Shinto C V <11365900+cshintov@users.noreply.github.com> Date: Fri, 6 Nov 2026 08:12:16 +0530 Subject: [PATCH 03/13] docs: the kernel contract's qwen27 attention and the 35B-A3B's routed widths --- docs/kernel-contract.md | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/docs/kernel-contract.md b/docs/kernel-contract.md index 1e9ec3f2dc9..a1d85e9f44b 100644 --- a/docs/kernel-contract.md +++ b/docs/kernel-contract.md @@ -506,6 +506,15 @@ Ornith-1.5-122B's routed block on Metal registers the experts' decode rows with (`q27_rows_extra`, 4 and 8 bits), the router's softmax and top-k with renormalized bf16 weights (`q27_route`: picks equal to the host's, each weight within float64's range at its bf16 points), the tensor units' expert sort and gather (bit for bit), the experts' SwiGLU, and the weighted combine with the gated shared expert (in place and from its slot). +The same kernels register at Qwen3.6-35B-A3B's served widths (experts of 512 over 2,048). +qwen27's attention registers at the 27B's 24 query heads over 4 and the 35B-A3B's 16 over 2: a round's rows through the +engine's own plan and launcher against float64 attention, prompt rows through the prompt kernel on every chip that +builds it (`attention_prompt_sg` before the M5), and attention_io's packing, append and keep checked bit for bit (keep +a second time on the caches the first left). A plan check shows the decode shapes plan prefix_1 to _6 for chains and +_2 to _6 for trees, and a tree over two tail chunks. Its known finding: before the M5 a masked key's zero probability +times an infinite value gives NaN in P V. Its controls: a row seeing one key past its own, the one-Mac merge dropping +a round's later tail chunks, the prompt kernel losing its bounded last step, and an append one row late. prefix_5 and +_6 have no launch record yet: past 256 threads they need a reserved thread count before M1 and M2 can admit them. GLM's Metal window projections register narrow and wide rows at 2, 3, 4, 5, 6 and 8 bits, plus both gathered paths. Independent FP64 linear cases accompany byte replacements against frozen pre-window-optimization kernels. The gathered SwiGLU keeps its predecessor's clipped BF16 output and nonfinite rules; gate/up taps qualify its dots separately. From 19703ea5399820827b15320a8c01bae33e780ddc Mon Sep 17 00:00:00 2001 From: Shinto C V <11365900+cshintov@users.noreply.github.com> Date: Fri, 6 Nov 2026 08:12:40 +0530 Subject: [PATCH 04/13] qwen27, contract: comments on one line within 120 columns (lean) --- zig/tests/contract/metal_affine_gather.zig | 3 +-- zig/tests/contract/metal_qwen27_moe.zig | 2 +- 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/zig/tests/contract/metal_affine_gather.zig b/zig/tests/contract/metal_affine_gather.zig index 1f6d41ec164..c8588f53f5a 100644 --- a/zig/tests/contract/metal_affine_gather.zig +++ b/zig/tests/contract/metal_affine_gather.zig @@ -76,8 +76,7 @@ const offset_inf = c.Known{ .gate = .nonfinite, .finding = "an infinite input gi pub fn spec(v: Variant) c.Spec { const known = if (v.bits == 4 and v.mutation == .none and !v.glm_m3_fast) offset_inf else null; - // Ornith-1.5-122B: gate and up 1024 x 3072, down 3072 x 1024; 32 rows an expert (32-row tiles), past 64 (64-row); - // Qwen3.6-35B-A3B: gate and up 512 x 2048, down 2048 x 512 + // Ornith-1.5-122B's experts (1024 x 3072, 3072 x 1024), then Qwen3.6-35B-A3B's (512 x 2048, 2048 x 512) const served = &[_]c.Shape{ .{ .rows = 256, .n = 1024, .k = 3072 }, .{ .rows = 520, .n = 3072, .k = 1024 }, .{ .rows = 256, .n = 512, .k = 2048 }, .{ .rows = 520, .n = 2048, .k = 512 } }; return .{ .name = name(v), .accum = .f32, .depth = groupDepth64, .out = .bf16, .known = known, .replaces = if (v.identity) "the frozen affine_mm before exact-nonfinite groups" else null, .tiles = .{ .{ .size = 32 }, .{ .size = 64, .step = 64, .min = 64 }, .{ .size = 128, .step = 64, .min = 64 } }, .served = served }; } diff --git a/zig/tests/contract/metal_qwen27_moe.zig b/zig/tests/contract/metal_qwen27_moe.zig index 6fb2f035680..c3b5d54b597 100644 --- a/zig/tests/contract/metal_qwen27_moe.zig +++ b/zig/tests/contract/metal_qwen27_moe.zig @@ -78,7 +78,7 @@ pub const Extra = struct { .depth = rowDepth, .out = .bf16, .tiles = .{ .{ .size = 2 }, .{ .size = 8, .step = 8, .min = 8 }, .{ .size = 512, .step = 64, .min = 64 } }, - // Ornith's decode windows: gate and up (1,024 over 3,072), down (3,072 over 1,024); the 35B-A3B's (512 over 2,048) + // decode windows: Ornith's gate and up (1,024 over 3,072) and down, then the 35B-A3B's (512 over 2,048) .served = &.{ .{ .rows = 16, .n = 1024, .k = 3072 }, .{ .rows = 1, .n = 3072, .k = 1024 }, .{ .rows = 16, .n = 512, .k = 2048 }, .{ .rows = 1, .n = 2048, .k = 512 } }, }; } From b7c28ae37976520ed05a8084019d4db3400148d6 Mon Sep 17 00:00:00 2001 From: Shinto C V <11365900+cshintov@users.noreply.github.com> Date: Fri, 6 Nov 2026 08:12:40 +0530 Subject: [PATCH 05/13] qwen27: staged references on Metal (tf-qwen27-run --stages) against a float64 forward One stage vocabulary (families/qwen3_5/stages.zig): the residual stream after the embedding and after each layer's mixer and MLP, then final (the normed rows the head reads, not the residual) and the logits. tools/zig/qwen36_stage_ref.py measures each against float64 of the checkpoint's exact weights; a non-unit final norm fixture refuses a residual labelled final. --- tools/zig/qwen36_f64.py | 223 +++++++++++++++ tools/zig/qwen36_mlx_stages.py | 96 +++++++ tools/zig/qwen36_stage_ref.py | 227 +++++++++++++++ tools/zig/qwen36_stage_ref_test.py | 153 ++++++++++ zig/qwen27_core.zig | 2 + zig/qwen27_speed_core.zig | 1 + zig/src/families/qwen27/decode_round.zig | 17 +- zig/src/families/qwen27/forward.zig | 15 + zig/src/families/qwen27/qwen27.zig | 4 + zig/src/families/qwen27/stage_planes.zig | 36 +++ zig/src/families/qwen3_5/stages.zig | 346 +++++++++++++++++++++++ zig/tests/qwen27/run.zig | 19 +- 12 files changed, 1136 insertions(+), 3 deletions(-) create mode 100644 tools/zig/qwen36_f64.py create mode 100644 tools/zig/qwen36_mlx_stages.py create mode 100644 tools/zig/qwen36_stage_ref.py create mode 100644 tools/zig/qwen36_stage_ref_test.py create mode 100644 zig/src/families/qwen27/stage_planes.zig create mode 100644 zig/src/families/qwen3_5/stages.zig diff --git a/tools/zig/qwen36_f64.py b/tools/zig/qwen36_f64.py new file mode 100644 index 00000000000..97be9020f0d --- /dev/null +++ b/tools/zig/qwen36_f64.py @@ -0,0 +1,223 @@ +"""A float64 qwen3_5_moe forward of an MLX affine checkpoint, exact weights, mlx_lm 0.31's math; no rounding.""" +from __future__ import annotations + +import json +from pathlib import Path + +import mlx.core as mx +import numpy as np + +F = np.float64 + + +def softplus(x): + return np.logaddexp(0.0, x) + + +def sigmoid(x): + return 1.0 / (1.0 + np.exp(-x)) + + +def silu(x): + return x * sigmoid(x) + + +def rms(x, weight, eps): + y = x / np.sqrt(np.mean(x * x, axis=-1, keepdims=True) + eps) + return y if weight is None else y * weight + + +def delta_rule(q, k, v, g, beta): + """The gated delta rule from a zero state: q, k [T, Hk, Dk]; v [T, Hv, Dv]; g, beta [T, Hv]; returns [T, Hv, Dv].""" + t, hv = v.shape[0], v.shape[1] + q, k = np.repeat(q, hv // q.shape[1], axis=1), np.repeat(k, hv // k.shape[1], axis=1) + state = np.zeros((hv, v.shape[2], k.shape[2])) + ys = np.empty(v.shape) + for i in range(t): + state *= g[i][:, None, None] + delta = (v[i] - (state @ k[i][:, :, None])[..., 0]) * beta[i][:, None] + state += delta[:, :, None] * k[i][:, None, :] + ys[i] = (state @ q[i][:, :, None])[..., 0] + return ys + + +class Checkpoint: + """The text model's tensors by name, dequantized to float64 on request.""" + + def __init__(self, snapshot: Path): + self.snapshot = snapshot + config = json.loads((snapshot / "config.json").read_text()) + self.config = config.get("text_config", config) + quant = config["quantization"] + self.bits, self.group = quant["bits"], quant["group_size"] + self.widths = {k: v for k, v in quant.items() if isinstance(v, dict)} + index = json.loads((snapshot / "model.safetensors.index.json").read_text())["weight_map"] + self.shards = {} + for name in sorted(set(index.values())): + self.shards.update(mx.load(str(snapshot / name))) + self.prefix = "language_model.model." + + def raw(self, name): + return self.shards[name] + + def vector(self, name): + return np.array(self.raw(name).astype(mx.float32)).astype(F) + + def width(self, module): + w = self.widths.get(module, {}) + return w.get("bits", self.bits), w.get("group_size", self.group) + + def dense(self, module, rows=None, index=None): + """`module`'s weight [out, in] (or expert `index`'s), only `rows` of out when given.""" + bits, group = self.width(module) + q, s, b = (self.raw(f"{module}.{k}") for k in ("weight", "scales", "biases")) + if index is not None: + q, s, b = q[index], s[index], b[index] + if rows is not None: + q, s, b = q[rows], s[rows], b[rows] + q = np.array(q) + s = np.array(s.astype(mx.float32)).astype(F) + b = np.array(b.astype(mx.float32)).astype(F) + per = 32 // bits + shifts = (np.arange(per, dtype=np.uint32) * bits).astype(np.uint32) + values = (q[..., None] >> shifts) & np.uint32((1 << bits) - 1) + values = values.reshape(*q.shape[:-1], -1).astype(F) + grouped = values.reshape(*values.shape[:-1], -1, group) + return (grouped * s[..., None] + b[..., None]).reshape(values.shape) + + +class Model: + def __init__(self, ckpt: Checkpoint): + c = ckpt.config + self.ck = ckpt + self.layers = c["num_hidden_layers"] + self.hidden = c["hidden_size"] + self.vocab = c["vocab_size"] + self.eps = c["rms_norm_eps"] + self.types = c["layer_types"] + self.k_heads, self.v_heads = c["linear_num_key_heads"], c["linear_num_value_heads"] + self.k_dim, self.v_dim = c["linear_key_head_dim"], c["linear_value_head_dim"] + self.heads, self.kv_heads, self.head_dim = c["num_attention_heads"], c["num_key_value_heads"], c["head_dim"] + rope = c["rope_parameters"] + self.rotary = int(self.head_dim * rope["partial_rotary_factor"]) + self.theta = float(rope["rope_theta"]) + self.experts, self.top_k = c["num_experts"], c["num_experts_per_tok"] + + def p(self, layer, rest): + return f"{self.ck.prefix}layers.{layer}.{rest}" + + def embed(self, ids): + return self.ck.dense(self.ck.prefix + "embed_tokens", rows=mx.array(np.asarray(ids, np.int32))) + + def mixer(self, layer, xs, positions): + """xs: the stream rows of one or more independent runs, each [T, hidden]; returns their mixer outputs.""" + norm = self.ck.vector(self.p(layer, "input_layernorm.weight")) + normed = [rms(x, norm, self.eps) for x in xs] + if self.types[layer] == "linear_attention": + return self.gdn(layer, normed) + return self.attention(layer, normed, positions) + + def gdn(self, layer, xs): + m = lambda n: self.ck.dense(self.p(layer, f"linear_attn.{n}")) + wqkv, wz, wa, wb, wo = m("in_proj_qkv"), m("in_proj_z"), m("in_proj_a"), m("in_proj_b"), m("out_proj") + conv = self.ck.vector(self.p(layer, "linear_attn.conv1d.weight"))[:, :, 0] # [channels, kernel] + a_log = self.ck.vector(self.p(layer, "linear_attn.A_log")) + dt_bias = self.ck.vector(self.p(layer, "linear_attn.dt_bias")) + gain = self.ck.vector(self.p(layer, "linear_attn.norm.weight")) + kd, vd, hk, hv = self.k_dim, self.v_dim, self.k_heads, self.v_heads + key = kd * hk + out = [] + for x in xs: + t = x.shape[0] + qkv = x @ wqkv.T + z = (x @ wz.T).reshape(t, hv, vd) + g = np.exp(-np.exp(a_log) * softplus(x @ wa.T + dt_bias)) + beta = sigmoid(x @ wb.T) + padded = np.concatenate([np.zeros((conv.shape[1] - 1, qkv.shape[1])), qkv]) + mixed = sum(padded[j:j + t] * conv[:, j] for j in range(conv.shape[1])) + mixed = silu(mixed) + q = mixed[:, :key].reshape(t, hk, kd) + k = mixed[:, key:2 * key].reshape(t, hk, kd) + v = mixed[:, 2 * key:].reshape(t, hv, vd) + q = rms(q, None, 1e-6) * kd ** -1.0 + k = rms(k, None, 1e-6) * kd ** -0.5 + y = rms(delta_rule(q, k, v, g, beta), gain, self.eps) * silu(z) + out.append(y.reshape(t, hv * vd) @ wo.T) + return out + + def rope(self, x, positions): + half = self.rotary // 2 + freq = self.theta ** (-np.arange(half, dtype=F) * 2.0 / self.rotary) + angle = np.asarray(positions, F)[:, None] * freq[None, :] + cos, sin = np.cos(angle)[:, None, :], np.sin(angle)[:, None, :] + x1, x2 = x[..., :half], x[..., half:self.rotary] + return np.concatenate([x1 * cos - x2 * sin, x1 * sin + x2 * cos, x[..., self.rotary:]], axis=-1) + + def attention(self, layer, xs, positions): + m = lambda n: self.ck.dense(self.p(layer, f"self_attn.{n}")) + wq, wk, wv, wo = m("q_proj"), m("k_proj"), m("v_proj"), m("o_proj") + qn = self.ck.vector(self.p(layer, "self_attn.q_norm.weight")) + kn = self.ck.vector(self.p(layer, "self_attn.k_norm.weight")) + h, kvh, d = self.heads, self.kv_heads, self.head_dim + out = [] + for x in xs: + t = x.shape[0] + qg = (x @ wq.T).reshape(t, h, 2 * d) + q, gate = qg[..., :d], qg[..., d:].reshape(t, h * d) + k = (x @ wk.T).reshape(t, kvh, d) + v = (x @ wv.T).reshape(t, kvh, d) + q = self.rope(rms(q, qn, self.eps), positions) + k = self.rope(rms(k, kn, self.eps), positions) + k, v = np.repeat(k, h // kvh, axis=1), np.repeat(v, h // kvh, axis=1) + scores = np.einsum("thd,shd->hts", q, k) * d ** -0.5 + scores = np.where(np.tril(np.ones((t, t), bool))[None], scores, -np.inf) + scores = np.exp(scores - scores.max(axis=-1, keepdims=True)) + scores /= scores.sum(axis=-1, keepdims=True) + o = np.einsum("hts,shd->thd", scores, v).reshape(t, h * d) + out.append((o * sigmoid(gate)) @ wo.T) + return out + + def route(self, logits): + """Top-k experts per row (ties to the lower id), their renormalized weights, the k-th/(k+1)-th gap.""" + order = np.argsort(-logits, axis=-1, kind="stable") + picks = order[:, :self.top_k] + top = np.take_along_axis(logits, picks, axis=-1) + weights = np.exp(top - top[:, :1]) + weights /= weights.sum(axis=-1, keepdims=True) + nxt = np.take_along_axis(logits, order[:, self.top_k:self.top_k + 1], axis=-1)[:, 0] + return picks, weights, top[:, -1] - nxt + + def moe(self, layer, xs): + """xs: stream rows after the mixer; returns each run's MLP output and per-row routing (picks, k/k+1 gap).""" + norm = self.ck.vector(self.p(layer, "post_attention_layernorm.weight")) + sizes = [x.shape[0] for x in xs] + x = rms(np.concatenate(xs), norm, self.eps) + logits = x @ self.ck.dense(self.p(layer, "mlp.gate")).T + picks, weights, gap = self.route(logits) + y = np.zeros_like(x) + base = self.p(layer, "mlp.switch_mlp") + for e in np.unique(picks): + rows, slot = np.nonzero(picks == e) + g = self.ck.dense(f"{base}.gate_proj", index=int(e)) + u = self.ck.dense(f"{base}.up_proj", index=int(e)) + dn = self.ck.dense(f"{base}.down_proj", index=int(e)) + xe = x[rows] + y[rows] += weights[rows, slot][:, None] * ((silu(xe @ g.T) * (xe @ u.T)) @ dn.T) + s = lambda n: self.ck.dense(self.p(layer, f"mlp.shared_expert.{n}")) + shared = (silu(x @ s("gate_proj").T) * (x @ s("up_proj").T)) @ s("down_proj").T + y += sigmoid(x @ self.ck.dense(self.p(layer, "mlp.shared_expert_gate")).T) * shared + cuts = np.cumsum(sizes)[:-1] + return np.split(y, cuts), np.split(picks, cuts), np.split(gap, cuts) + + def final(self, x): + return rms(x, self.ck.vector(self.ck.prefix + "norm.weight"), self.eps) + + def head(self, xs, chunk=16384): + """Logits for each run's rows, the head dequantized a vocab chunk at a time.""" + sizes = [x.shape[0] for x in xs] + x = np.concatenate(xs) + out = np.empty((x.shape[0], self.vocab)) + for at in range(0, self.vocab, chunk): + rows = mx.arange(at, min(at + chunk, self.vocab)) + out[:, at:at + chunk] = x @ self.ck.dense("language_model.lm_head", rows=rows).T + return np.split(out, np.cumsum(sizes)[:-1]) diff --git a/tools/zig/qwen36_mlx_stages.py b/tools/zig/qwen36_mlx_stages.py new file mode 100644 index 00000000000..d68ea1d9295 --- /dev/null +++ b/tools/zig/qwen36_mlx_stages.py @@ -0,0 +1,96 @@ +"""mlx_lm's staged references for qwen3_5_moe, in the layout families/qwen3_5/stages.zig writes (see USAGE).""" +from __future__ import annotations + +USAGE = """The rows follow mlx_lm's generate_step: the prompt but its last token in one call, then one-row steps +feeding the last prompt token and every teacher token but the last; logits are each step's row. The decoder layer +runs its own ops unchanged and records the stream after the mixer and after the MLP. + + python tools/zig/qwen36_mlx_stages.py --snapshot SNAP --ids ids.json --reference ref.json --out DIR""" + +import argparse +import json +from pathlib import Path + +import mlx.core as mx +import numpy as np +from mlx_lm import load +from mlx_lm.models import qwen3_5 +from mlx_lm.models.cache import make_prompt_cache + +RECORD: list | None = None + + +def decoder_call(self, x, mask=None, cache=None): + if self.is_linear: + r = self.linear_attn(self.input_layernorm(x), mask, cache) + else: + r = self.self_attn(self.input_layernorm(x), mask, cache) + h = x + r + out = h + self.mlp(self.post_attention_layernorm(h)) + if RECORD is not None: + RECORD.append((h, out)) + return out + + +def raw(x): + x = x.astype(mx.bfloat16) + mx.eval(x) + return np.array(x.view(mx.uint16)).reshape(-1, x.shape[-1]) + + +def main(): + global RECORD + ap = argparse.ArgumentParser(description=__doc__ + "\n\n" + USAGE, formatter_class=argparse.RawDescriptionHelpFormatter) + ap.add_argument("--snapshot", type=Path, required=True) + ap.add_argument("--ids", type=Path, required=True) + ap.add_argument("--reference", type=Path, required=True) + ap.add_argument("--out", type=Path, required=True) + args = ap.parse_args() + prompt = json.loads(args.ids.read_text()) + reference = json.loads(args.reference.read_text()) + + qwen3_5.DecoderLayer.__call__ = decoder_call + model, _ = load(str(args.snapshot)) + text = model.language_model.model + layers = len(text.layers) + names = ["embed"] + [f"l{l:02d}.{k}" for l in range(layers) for k in ("mixer", "block")] + ["final"] + planes = {n: [] for n in names + ["logits"]} + cache = make_prompt_cache(model) + if len(prompt) < 2: + raise SystemExit("the prompt needs two tokens: one prefill call, then the steps") + calls = [prompt[:-1], [prompt[-1]]] + [[t] for t in reference[:-1]] + picks = [] + for step, ids in enumerate(calls): + tokens = mx.array(ids)[None] + RECORD = [] + logits = model(tokens, cache=cache) + mx.eval(logits, [c.state for c in cache]) + planes["embed"].append(raw(text.embed_tokens(tokens))) + for l, (h, out) in enumerate(RECORD): + planes[f"l{l:02d}.mixer"].append(raw(h)) + planes[f"l{l:02d}.block"].append(raw(out)) + planes["final"].append(raw(text.norm(RECORD[-1][1]))) + if step > 0: + last = logits[:, -1, :] + planes["logits"].append(raw(last)) + logprobs = last - mx.logsumexp(last, keepdims=True) + picks.append(int(mx.argmax(logprobs, axis=-1).item())) + RECORD = None + args.out.mkdir(parents=True, exist_ok=True) + stages = [] + for n, chunks in planes.items(): + data = np.concatenate(chunks) + data.tofile(args.out / f"{n}.bf16") + stages.append({"name": n, "width": int(data.shape[1]), "rows": int(data.shape[0])}) + total = len(prompt) + len(reference) - 1 + index = {"version": 1, "dtype": "bf16", "layers": layers, "hidden": stages[0]["width"], + "vocab": stages[-1]["width"], "stages": stages, "positions": list(range(total)), + "logit_positions": list(range(len(prompt) - 1, total)), + "mlx": mx.__version__, "greedy_picks_equal_reference": picks == reference, "picks": picks} + (args.out / "index.json").write_text(json.dumps(index)) + print(json.dumps({"picks_equal_reference": picks == reference, + "differ_at": [i for i, (a, b) in enumerate(zip(picks, reference)) if a != b]})) + + +if __name__ == "__main__": + main() diff --git a/tools/zig/qwen36_stage_ref.py b/tools/zig/qwen36_stage_ref.py new file mode 100644 index 00000000000..7f74b223290 --- /dev/null +++ b/tools/zig/qwen36_stage_ref.py @@ -0,0 +1,227 @@ +"""Staged references for qwen3_5_moe: engine stage dumps against a float64 forward of the same checkpoint.""" +from __future__ import annotations + +USAGE = """Each engine directory holds what families/qwen3_5/stages.zig writes (or qwen36_mlx_stages.py): one bf16 +file per stage (embed, lNN.mixer, lNN.block, final, logits) and index.json with every row's cache position. + local float64 of one stage fed the engine's own bf16 input to it: that stage's error alone. + chained float64 from the token ids: the accumulated error. +Per stage and engine: the worst row's relative error and its worst element in bf16 steps of the row's largest value. +At the asked teacher positions: every contender's logit in float64, chained and fed each engine's final norm. + + python tools/zig/qwen36_stage_ref.py --snapshot SNAP --ids ids.json --reference ref.json \\ + --engine metal=DIR --engine mlx=DIR --positions 24,39,44,54 --out stages.json""" + +import argparse +import json +import sys +import time +from pathlib import Path + +import numpy as np + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +from qwen36_f64 import Checkpoint, Model # noqa: E402 + + +def stage_names(layers): + names = ["embed"] + for l in range(layers): + names += [f"l{l:02d}.mixer", f"l{l:02d}.block"] + return names + ["final", "logits"] + + +def bf16(raw): + return (raw.astype(np.uint32) << 16).view(np.float32).astype(np.float64) + + +class Dump: + """One engine's stage directory; refuses a missing stage, a wrong shape or rows at other positions.""" + + def __init__(self, name, path: Path, layers, hidden, vocab, positions, logit_positions): + self.name, self.path = name, path + index = json.loads((path / "index.json").read_text()) + if (index.get("version"), index.get("dtype")) != (1, "bf16"): + raise SystemExit(f"{name}: index version {index.get('version')} / {index.get('dtype')} is not 1 / bf16") + if (index["layers"], index["hidden"], index["vocab"]) != (layers, hidden, vocab): + raise SystemExit(f"{name}: shape {index['layers']}/{index['hidden']}/{index['vocab']} is not the model's") + # Logits may cover more rows (a one-row-step engine has every row's); the teacher rows are taken from them. + have = {p: i for i, p in enumerate(index["logit_positions"])} + if len(have) != len(index["logit_positions"]): + raise SystemExit(f"{name}: logit positions repeat") + if index["positions"] != positions or any(p not in have for p in logit_positions): + raise SystemExit(f"{name}: rows are not positions {positions[0]}..{positions[-1]} / logits {logit_positions[0]}..") + self.logit_rows = np.array([have[p] for p in logit_positions]) + listed = {s["name"]: s for s in index["stages"]} + if len(listed) != len(index["stages"]) or sorted(listed) != sorted(stage_names(layers)): + raise SystemExit(f"{name}: stages differ from {len(stage_names(layers))} expected, once each") + # Every plane's shape from the model and the positions, never from the stage's own entry. + want = {n: (len(have), vocab) if n == "logits" else (len(positions), hidden) for n in listed} + for n, s in listed.items(): + if (s["rows"], s["width"]) != want[n]: + raise SystemExit(f"{name}: {n} is {s['rows']}x{s['width']}, not {want[n][0]}x{want[n][1]}") + self.rows = {n: w[0] for n, w in want.items()} + self.width = {n: w[1] for n, w in want.items()} + # An engine whose own pick is not its logits' first maximum (mlx_lm argmaxes its log-probabilities) lists it. + self.picks = np.array(index["picks"]) if "picks" in index else None + + def get(self, stage): + raw = np.fromfile(self.path / f"{stage}.bf16", dtype=np.uint16) + if raw.size != self.rows[stage] * self.width[stage]: + raise SystemExit(f"{self.name}: {stage}.bf16 has {raw.size} values") + rows = bf16(raw.reshape(self.rows[stage], self.width[stage])) + return rows[self.logit_rows] if stage == "logits" else rows + + +def step(v): + """A bf16 step at |v|: 2^(exponent - 7).""" + v = np.maximum(np.abs(v), np.finfo(np.float32).tiny) + return np.exp2(np.floor(np.log2(v)) - 7) + + +def measure(engine, ref, rows_of_interest): + """Per row: ||e - r|| / ||r|| and max|e - r| in bf16 steps of max|r|; the worst row and the asked rows.""" + diff = engine - ref + rel = np.linalg.norm(diff, axis=1) / np.maximum(np.linalg.norm(ref, axis=1), 1e-300) + steps = np.abs(diff).max(axis=1) / step(np.abs(ref).max(axis=1)) + worst = int(np.argmax(rel)) + return { + "max_rel": float(rel.max()), "median_rel": float(np.median(rel)), "worst_row": worst, + "max_steps": float(steps.max()), "median_steps": float(np.median(steps)), + "rows": {str(k): {"rel": float(rel[r]), "steps": float(steps[r])} for k, r in rows_of_interest.items()}, + } + + +def outliers(engine, local, gap, factor=5.0, most=8): + """Rows whose MLP error is `factor` times the median, with the float64 router's k-th/(k+1)-th gap.""" + rel = np.linalg.norm(engine - local, axis=1) / np.linalg.norm(local, axis=1) + rows = np.nonzero(rel > factor * np.median(rel))[0] + rows = rows[np.argsort(-rel[rows])][:most] + return [[int(r), float(rel[r]), float(gap[r])] for r in rows] + + +def top1_summary(chained, picks): + """Float64 top two and margin per position; per engine, where it picks another token and how far below (steps).""" + order = np.argsort(-chained, axis=1, kind="stable")[:, :2] + top = np.take_along_axis(chained, order, axis=1) + margin = top[:, 0] - top[:, 1] + out = {"f64_margin_steps": [float(x) for x in margin / step(top[:, 0])], "engines": {}} + for name, pick in picks.items(): + pick = np.asarray(pick) + wrong = np.nonzero(pick != order[:, 0])[0] + out["engines"][name] = { + "matches_f64": int(len(pick) - len(wrong)), "of": len(pick), + "other": [[int(p), int(pick[p]), int(order[p, 0]), + float((top[p, 0] - chained[p, pick[p]]) / step(top[p, 0]))] for p in wrong]} + return out + + +def contenders(teacher, dumps, logits, reference_token): + ids = {int(reference_token)} + for d in dumps: + ids.update(int(i) for i in np.argsort(-logits[d.name][teacher], kind="stable")[:2]) + return sorted(ids) + + +def main(): + ap = argparse.ArgumentParser(description=__doc__ + "\n\n" + USAGE, formatter_class=argparse.RawDescriptionHelpFormatter) + ap.add_argument("--snapshot", type=Path, required=True) + ap.add_argument("--ids", type=Path, required=True) + ap.add_argument("--reference", type=Path, required=True, help="teacher tokens; every one but the last is fed") + ap.add_argument("--engine", action="append", default=[], help="NAME=DIR, repeatable") + ap.add_argument("--logits", action="append", default=[], + help="NAME=FILE: an engine's bf16 logits for every fed row (tf-qwen35-cuda step), top-1 only") + ap.add_argument("--positions", default="24,39,44,54", help="teacher positions to report in full") + ap.add_argument("--out", type=Path, required=True) + ap.add_argument("--layers", type=int, default=0, help="stop after this many layers (a quick check)") + args = ap.parse_args() + + prompt = json.loads(args.ids.read_text()) + reference = json.loads(args.reference.read_text()) + tokens = prompt + reference[:-1] + positions = list(range(len(tokens))) + logit_positions = positions[len(prompt) - 1:] + asked = [int(p) for p in args.positions.split(",") if p] + asked_rows = {p: len(prompt) - 1 + p for p in asked} + + t0 = time.time() + model = Model(Checkpoint(args.snapshot)) + layers = args.layers or model.layers + dumps = [] + for spec in args.engine: + name, _, path = spec.partition("=") + dumps.append(Dump(name, Path(path), model.layers, model.hidden, model.vocab, positions, logit_positions)) + if not dumps: + raise SystemExit("no --engine") + + result = {"tokens": len(tokens), "prompt": len(prompt), "engines": [d.name for d in dumps], "stages": {}, + "routing": {}, "teacher": {}} + + def record(stage, local, chained): + rows = {p: p for p in asked} if stage == "logits" else asked_rows + result["stages"][stage] = { + d.name: {"local": measure(d.get(stage), local[i], rows), + "chained": measure(d.get(stage), chained, rows)} for i, d in enumerate(dumps)} + + x = model.embed(tokens) + record("embed", [x] * len(dumps), x) + prev = {d.name: d.get("embed") for d in dumps} + for layer in range(layers): + mixed = model.mixer(layer, [x] + [prev[d.name] for d in dumps], positions) + h = x + mixed[0] + local = [prev[d.name] + mixed[1 + i] for i, d in enumerate(dumps)] + name = f"l{layer:02d}.mixer" + record(name, local, h) + after = {d.name: d.get(name) for d in dumps} + y, picks, gap = model.moe(layer, [h] + [after[d.name] for d in dumps]) + x = h + y[0] + local = [after[d.name] + y[1 + i] for i, d in enumerate(dumps)] + name = f"l{layer:02d}.block" + record(name, local, x) + result["routing"][f"l{layer:02d}"] = { + "chained_gap": {str(p): float(gap[0][r]) for p, r in asked_rows.items()}, + **{d.name: {"rows_with_other_picks": int((np.sort(picks[1 + i], 1) != np.sort(picks[0], 1)).any(1).sum()), + "asked_other_picks": {str(p): bool((np.sort(picks[1 + i][r]) != np.sort(picks[0][r])).any()) + for p, r in asked_rows.items()}, + "outliers": outliers(d.get(name), local[i], gap[1 + i])} + for i, d in enumerate(dumps)}} + prev = {d.name: d.get(name) for d in dumps} + print(f"layer {layer} {time.time() - t0:.0f}s", file=sys.stderr, flush=True) + + if layers == model.layers: + final = model.final(x) + record("final", [model.final(prev[d.name]) for d in dumps], final) + engine_final = {d.name: d.get("final") for d in dumps} + lp = np.array(logit_positions) + heads = model.head([final[lp]] + [engine_final[d.name][lp] for d in dumps]) + record("logits", heads[1:], heads[0]) + logits = {d.name: d.get("logits") for d in dumps} + for p in asked: + ids = contenders(p, dumps, logits, reference[p]) + chained = heads[0][p] + best = np.argsort(-chained, kind="stable")[:3] + result["teacher"][str(p)] = { + "reference_token": int(reference[p]), + "f64_chained_top3": [[int(i), float(chained[i])] for i in best], + "contenders": {str(i): { + "f64_chained": float(chained[i]), + **{f"f64_from_{d.name}_final": float(heads[1 + k][p][i]) for k, d in enumerate(dumps)}, + **{d.name: float(logits[d.name][p][i]) for d in dumps}} for i in ids}, + "top2": {d.name: [int(i) for i in np.argsort(-logits[d.name][p], kind="stable")[:2]] for d in dumps}, + } + picks = {d.name: d.picks if d.picks is not None else np.argmax(logits[d.name], 1) for d in dumps} + for spec in args.logits: + name, _, path = spec.partition("=") + raw = np.fromfile(path, dtype=np.uint16) + if raw.size != len(tokens) * model.vocab: + raise SystemExit(f"{name}: {path} is not {len(tokens)} rows of {model.vocab} logits") + picks[name] = np.argmax(bf16(raw.reshape(len(tokens), model.vocab)[lp]), 1) + picks["reference"] = np.array(reference) + result["top1"] = top1_summary(heads[0], picks) + + result["seconds"] = time.time() - t0 + args.out.write_text(json.dumps(result, indent=1)) + print(f"wrote {args.out} in {result['seconds']:.0f}s", file=sys.stderr) + + +if __name__ == "__main__": + main() diff --git a/tools/zig/qwen36_stage_ref_test.py b/tools/zig/qwen36_stage_ref_test.py new file mode 100644 index 00000000000..040d9c7e679 --- /dev/null +++ b/tools/zig/qwen36_stage_ref_test.py @@ -0,0 +1,153 @@ +"""The float64 reference's pieces against mlx's own ops, and the staged comparer's refusals and planted errors.""" +import json +import tempfile +import unittest +from pathlib import Path + +import mlx.core as mx +import numpy as np +from mlx_lm.models.gated_delta import gated_delta_ops + +from qwen36_f64 import Checkpoint, Model, delta_rule, rms +from qwen36_stage_ref import Dump, bf16, measure, stage_names, step + + +def tiny_checkpoint(bits, out_rows=8, width=128, group=64): + """A Checkpoint whose one tensor `w` is mlx-quantized from random weights, without a snapshot on disk.""" + ck = Checkpoint.__new__(Checkpoint) + ck.bits, ck.group, ck.widths = bits, group, {} + w = mx.random.normal((out_rows, width), key=mx.random.key(bits)).astype(mx.bfloat16) + q, s, b = mx.quantize(w, group_size=group, bits=bits) + ck.shards = {"w.weight": q, "w.scales": s, "w.biases": b} + return ck, mx.dequantize(q, s, b, group_size=group, bits=bits).astype(mx.float32) + + +class ReferenceOpsTest(unittest.TestCase): + def test_dequantize_matches_mlx_for_every_width(self): + for bits in (4, 8): + ck, want = tiny_checkpoint(bits) + got = ck.dense("w") + # mlx dequantizes in bf16; ours is exact, so they agree to one bf16 step of each value. + np.testing.assert_allclose(got, np.array(want), rtol=2 ** -8, atol=1e-6) + np.testing.assert_array_equal(ck.dense("w", rows=mx.array([3, 1])), got[[3, 1]]) + + def test_rope_matches_mlx_fast_rope(self): + m = Model.__new__(Model) + m.rotary, m.theta = 64, 1e7 + x = np.random.default_rng(0).standard_normal((5, 2, 256)) + got = m.rope(x, np.arange(7, 12)) + want = mx.fast.rope(mx.array(x.transpose(1, 0, 2), mx.float32)[None], 64, traditional=False, base=1e7, + scale=1.0, offset=7) + np.testing.assert_allclose(got, np.array(want)[0].transpose(1, 0, 2), atol=2e-5) + + def test_delta_rule_matches_mlx_ops(self): + rng = np.random.default_rng(1) + t, hk, hv, d = 6, 2, 4, 16 + q, k = rng.standard_normal((t, hk, d)), rng.standard_normal((t, hk, d)) + v = rng.standard_normal((t, hv, d)) + g, beta = rng.uniform(0.5, 1.0, (t, hv)), rng.uniform(0.0, 1.0, (t, hv)) + f = lambda a: mx.array(a, mx.float32)[None] + want, _ = gated_delta_ops(f(q), f(k), f(v), f(g), f(beta)) + np.testing.assert_allclose(delta_rule(q, k, v, g, beta), np.array(want)[0], atol=1e-4) + + def test_route_breaks_ties_to_the_lower_id_and_renormalizes(self): + m = Model.__new__(Model) + m.top_k = 2 + picks, weights, gap = m.route(np.array([[1.0, 3.0, 3.0, 3.0]])) + np.testing.assert_array_equal(picks, [[1, 2]]) + np.testing.assert_allclose(weights, [[0.5, 0.5]]) + self.assertEqual(gap[0], 0.0) + + def test_rms(self): + x = np.array([[3.0, 4.0]]) + np.testing.assert_allclose(rms(x, np.array([2.0, 1.0]), 0.0), [[3 / np.sqrt(12.5) * 2, 4 / np.sqrt(12.5)]]) + + +def write_dump(path: Path, layers, hidden, vocab, rows, logits, positions=None, names=None, shapes=None, + logit_positions=None, version=1): + """Logits row i holds bf16(i); `shapes` overrides a stage's (rows, width) so only the shape check can refuse it.""" + path.mkdir(parents=True, exist_ok=True) + stages = [] + for n in names or stage_names(layers): + count, width = (shapes or {}).get(n, (logits, vocab) if n == "logits" else (rows, hidden)) + data = np.zeros((count, width), np.uint16) + if n == "logits": + data[:] = (np.arange(count, dtype=np.float32).view(np.uint32) >> 16).astype(np.uint16)[:, None] + data.tofile(path / f"{n}.bf16") + stages.append({"name": n, "width": width, "rows": count}) + index = {"version": version, "dtype": "bf16", "layers": layers, "hidden": hidden, "vocab": vocab, + "stages": stages, "positions": positions if positions is not None else list(range(rows)), + "logit_positions": logit_positions if logit_positions is not None else list(range(rows - logits, rows))} + (path / "index.json").write_text(json.dumps(index)) + + +class ComparerTest(unittest.TestCase): + def test_dump_refuses_other_shapes_positions_and_names(self): + with tempfile.TemporaryDirectory() as tmp: + good = Path(tmp) / "good" + write_dump(good, 2, 4, 6, 5, 2) + args = (2, 4, 6, list(range(5)), [3, 4]) + self.assertEqual(Dump("e", good, *args).get("l01.block").shape, (5, 4)) + # Each case's files agree with its own index, so only the check against the model can refuse it. + cases = { + "layers": dict(layers=3), "positions": dict(positions=[0, 1, 2, 4, 5]), + "names": dict(names=stage_names(2)[:-1]), "repeated": dict(names=stage_names(2) + ["final"]), + "version": dict(version=2), "repeated logits": dict(logit_positions=[3, 3]), + } + for n in ("embed", "l00.mixer", "l01.block", "final", "logits"): + rows, width = (2, 6) if n == "logits" else (5, 4) + for bad in ((rows, 1), (rows + 1, width), (rows - 1, width), (rows, width * 2)): + cases[f"{n} {bad}"] = dict(shapes={n: bad}) + for label, change in cases.items(): + path = Path(tmp) / label + kw = dict(layers=2, hidden=4, vocab=6, rows=5, logits=2) | change + write_dump(path, **kw) + with self.assertRaises(SystemExit, msg=label): + Dump("e", path, *args) + (good / "final.bf16").write_bytes(b"\0" * 6) + with self.assertRaises(SystemExit): + Dump("e", good, *args).get("final") + + def test_every_row_logits_give_the_teacher_rows_and_a_missing_row_is_refused(self): + with tempfile.TemporaryDirectory() as tmp: + every = Path(tmp) / "every" + write_dump(every, 1, 4, 6, 5, 5) # one-row steps: logits at positions 0..4 + got = Dump("e", every, 1, 4, 6, list(range(5)), [3, 4]).get("logits") + np.testing.assert_array_equal(got[:, 0], [3.0, 4.0]) + with self.assertRaises(SystemExit): + Dump("e", Path(tmp) / "every", 1, 4, 6, list(range(5)), [4, 5]) + + def test_step_is_bf16_spacing_at_every_exponent(self): + for e in range(-100, 100): + for mant in (1.0, 1.5, 1.9921875): + v = mant * 2.0 ** e + self.assertEqual(step(np.array([v]))[0], 2.0 ** (e - 7)) + self.assertEqual(step(np.array([-v]))[0], 2.0 ** (e - 7)) + + def test_a_planted_step_is_found_on_every_row(self): + rng = np.random.default_rng(2) + ref = bf16(rng.integers(0x3f00, 0x4100, (6, 8), dtype=np.uint16)) + for row in range(6): + for col in range(8): + for k in (1, 3): + engine = ref.copy() + engine[row, col] += k * step(np.abs(ref[row]).max(keepdims=True))[0] + m = measure(engine, ref, {"r": row}) + self.assertEqual(m["worst_row"], row) + self.assertAlmostEqual(m["max_steps"], k) + self.assertAlmostEqual(m["rows"]["r"]["steps"], k) + self.assertEqual(measure(ref, ref, {})["max_steps"], 0.0) + + def test_final_is_the_normed_head_input_not_the_residual(self): + # a non-unit final norm (gains far from 1, rows far from unit RMS): a residual labelled final cannot pass + rng = np.random.default_rng(3) + residual = rng.standard_normal((6, 64)) * 7.0 + gain = rng.uniform(0.2, 3.0, 64) + final = rms(residual, gain, 1e-6) + self.assertLess(measure(final.copy(), final, {})["max_rel"], 1e-12) + self.assertGreater(measure(residual, final, {})["max_rel"], 0.5) + self.assertGreater(measure(rms(residual, None, 1e-6), final, {})["max_rel"], 0.1) + + +if __name__ == "__main__": + unittest.main() diff --git a/zig/qwen27_core.zig b/zig/qwen27_core.zig index e461a9bc80a..89bea535ea6 100644 --- a/zig/qwen27_core.zig +++ b/zig/qwen27_core.zig @@ -11,6 +11,8 @@ pub const qwen_vl = @import("src/core/qwen_vl/qwen_vl.zig"); pub const segments = @import("src/core/segments.zig"); pub const prompt_tail = @import("src/core/prompt_tail.zig"); +/// Staged references: the qwen3_5 forward's stages and their on-disk layout (tools/zig/qwen36_stage_ref.py). +pub const qwen35_stages = @import("src/families/qwen3_5/stages.zig"); pub const checkpoint_host = checkpoint; pub const lane_projection = @import("core_lane"); diff --git a/zig/qwen27_speed_core.zig b/zig/qwen27_speed_core.zig index 49c70e2b9bc..152e6892abd 100644 --- a/zig/qwen27_speed_core.zig +++ b/zig/qwen27_speed_core.zig @@ -3,6 +3,7 @@ pub const tree_slots = @import("src/core/tree_slots.zig"); pub const recurrent_workspace = @import("src/core/recurrent_workspace.zig"); pub const gpu_profile = @import("src/core/gpu_profile.zig"); pub const checkpoint_host = @import("src/core/checkpoint.zig"); +pub const qwen35_stages = @import("src/families/qwen3_5/stages.zig"); pub const draft_ops = struct { pub const Ref = struct { buf: @import("metal").Buffer, off: usize = 0 }; diff --git a/zig/src/families/qwen27/decode_round.zig b/zig/src/families/qwen27/decode_round.zig index 215b87e059e..1b2884944b4 100644 --- a/zig/src/families/qwen27/decode_round.zig +++ b/zig/src/families/qwen27/decode_round.zig @@ -30,6 +30,7 @@ const kv_slots = @import("kv_slots.zig"); /// The host's hook for buffers a slot's K/V growth made. pub const Grown = struct { ctx: *anyopaque, added: *const fn (ctx: *anyopaque, buffers: []const mtl.Buffer) void }; +const staged = @import("core").qwen35_stages; /// Whether `cb` failed on the GPU; its Metal error (out of memory, a timeout) is logged with `what` it ran. pub fn gpuFailed(cb: mtl.CommandBuffer, what: []const u8) bool { const msg = cb.failure() orelse return false; @@ -66,6 +67,8 @@ pub const Runner = struct { capture_taps: bool = false, /// The last tapped pass's rows by slot: their cache start, first frame row and count (0: none held). tapped: [attn.planning.max_streams]Tapped = @splat(.{}), + /// Staged references for one stream's rounds; null (the default) records nothing. + stages: ?*@import("stage_planes.zig").Planes = null, tail: ?forward.Tail = null, accepted_chain: bool = false, /// The running pass's prompt tail start (prompt_tail.zig): its last layer's q, o and MLP run from this row on. @@ -281,6 +284,8 @@ pub const Runner = struct { // A rank's head writes only this rank's vocabulary columns; the tail's matcher reads the whole vocabulary. if (r.tail != null and r.reduce != null) return error.TailOnRank; for (round.slots, round.windows) |slot, window| if (slot >= r.ready or r.offsets[slot] != window.start) return error.CachePositionDiffers; + // staged references record one stream's chain with its head: refused before the round touches any state + if (r.stages != null) try staged.admit(round.windows.len, round.windows.len == 1 and staged.isChain(round.windows[0].parents), head != .none); for (round.slots, round.windows) |slot, window| try r.cover(slot, window.start + @as(u32, @intCast(window.parents.len))); for (round.slots, round.windows) |slot, window| try r.reserve(slot, window.start + @as(u32, @intCast(window.parents.len))); const paths = try r.allocator.alloc([]const u32, round.windows.len); @@ -322,6 +327,7 @@ pub const Runner = struct { r.taps.begin(); r.tapped = @splat(.{}); } + if (r.stages) |planes| planes.begin(); const pool = mtl.objc.Pool.push(); defer pool.pop(); const spanned = if (r.trace) |t| t.spanned else 0; // a profiled pass's spans commit buffers of their own @@ -331,7 +337,7 @@ pub const Runner = struct { defer r.tail_from = null; if (r.tail_from) |t0| r.model.frame.setTail(t0, @intCast(round.ids.len)); const keys = @import("prompt_tail.zig").keysOnly(tail_facts); - var stages = forward.Stages{ .model = r.model, .rows = @intCast(round.ids.len), .hooks = .{ .ptr = r, .gdn = gdnForward, .attention = attentionForward, .tap = if (r.capture_taps) tap else null, .keys = if (keys) prompt_tail.keysForward else null }, .head = head, .tail = r.tail, .images = placed.images, .reduce = r.reduce, .picks = r.picks, .tail_from = r.tail_from }; + var stages = forward.Stages{ .model = r.model, .rows = @intCast(round.ids.len), .hooks = .{ .ptr = r, .gdn = gdnForward, .attention = attentionForward, .tap = if (r.capture_taps) tap else null, .keys = if (keys) prompt_tail.keysForward else null, .stage = if (r.stages != null) stage else null }, .head = head, .tail = r.tail, .images = placed.images, .reduce = r.reduce, .picks = r.picks, .tail_from = r.tail_from }; r.last_gpu_seconds = @import("core").segments.runCommitting(r.model.device, &.{r.model.queue}, r.model.config.layers, .concurrent, &stages, commit_every) catch |err| { r.failed = true; return err; @@ -353,6 +359,10 @@ pub const Runner = struct { try r.taps.complete(); for (round.slots, round.windows, round.firsts) |slot, w, first| r.tapped[slot] = .{ .start = w.start, .first = first, .rows = @intCast(w.parents.len) }; } + if (r.stages) |planes| planes.end(round.windows[0].start) catch |err| { + r.failed = true; + return err; + }; if (accepted) { for (round.slots, round.windows) |slot, window| r.offsets[slot] = window.start + @as(u32, @intCast(window.parents.len)); } else r.active = fingerprint(round); @@ -572,6 +582,11 @@ pub const Runner = struct { const r: *Runner = @ptrCast(@alignCast(ptr)); try r.taps.record(r.model.glue, e, layer, hidden, rows); } + + fn stage(ptr: *anyopaque, e: mtl.ComputeEncoder, at: forward.Point, x: @import("projection.zig").Ref, rows: u32) !void { + const r: *Runner = @ptrCast(@alignCast(ptr)); + try r.stages.?.record(r.model.glue, e, at, x, rows); + } }; fn fingerprint(round: *const Round) [32]u8 { diff --git a/zig/src/families/qwen27/forward.zig b/zig/src/families/qwen27/forward.zig index 2b56a60697d..c698cfa10f1 100644 --- a/zig/src/families/qwen27/forward.zig +++ b/zig/src/families/qwen27/forward.zig @@ -16,7 +16,10 @@ pub const Mixer = struct { tap: ?*const fn (*anyopaque, mtl.ComputeEncoder, usize, Ref, u32) anyerror!void = null, /// A pass that keeps no row and has no other reader of the last layer: that layer writes keys and values only. keys: ?*const fn (*anyopaque, mtl.ComputeEncoder, usize, wts.Attention, *Frame, u32) anyerror!void = null, + /// Staged references (off unless asked for): the stream after each stage, the final norm and the head's rows. + stage: ?*const fn (*anyopaque, mtl.ComputeEncoder, Point, Ref, u32) anyerror!void = null, }; +pub const Point = @import("core").qwen35_stages.Point; /// One exchange: `x` its index, `ref` this rank's `width` columns of the seam in the window's slot for x. pub const Seam = struct { x: u32, ref: Ref }; @@ -101,6 +104,7 @@ pub const Stages = struct { m.glue.imageRows(lane.enc, s.hidden, rows, m.frame.get(.takes), @intCast(m.config.hidden), s.rows); lane.enc.barrier(); } + if (s.hooks.stage) |stage| try stage(s.hooks.ptr, lane.enc, .embed, s.hidden, s.rows); } pub fn wait(_: *Stages, _: usize) @import("core").segments.Wait { return .mixer; @@ -117,6 +121,7 @@ pub const Stages = struct { if (s.pending != null) { std.mem.swap(Ref, &s.hidden, &s.residual); if (s.hooks.tap) |tap| try tap(s.hooks.ptr, e, index - 1, s.hidden, s.rows); + if (s.hooks.stage) |stage| try stage(s.hooks.ptr, e, .{ .block = index - 1 }, s.hidden, s.rows); } } /// The last layer of a pass whose other rows nothing reads: q, attention, o and the MLP have no reader. @@ -173,6 +178,7 @@ pub const Stages = struct { try m.kernels.norm(e, t.at(s.hidden, h), t.at(f.get(.output), h), wts.ref(layer.post_norm), f.get(.eps), t.dims, t.at(s.residual, h), t.at(f.get(.input), h), t.sums(f.get(.sums)), h, t.n); e.barrier(); std.mem.swap(Ref, &s.hidden, &s.residual); + if (s.hooks.stage) |stage| try stage(s.hooks.ptr, e, .{ .mixer = index }, s.hidden, s.rows); if (layer.moe) |*mo| if (!m.moe.?.sorted(mo, m.kernels.prompt)) { // decode rows: the routed block runs the shared expert as one more slot of the experts' kernel try m.moe.?.block(lane.enc, m.config, mo, f, s.rows, m.kernels.prompt); @@ -264,6 +270,11 @@ pub const Stages = struct { e.barrier(); std.mem.swap(Ref, &s.hidden, &s.residual); if (s.hooks.tap) |tap| try tap(s.hooks.ptr, e, m.config.layers - 1, s.hidden, s.rows); + if (s.hooks.stage) |stage| { + // the last block is the residual stream; final is the normed rows the head reads (f.input) + try stage(s.hooks.ptr, e, .{ .block = m.config.layers - 1 }, s.hidden, s.rows); + try stage(s.hooks.ptr, e, .final, f.get(.input), s.rows); + } if (s.head == .all and s.rows > @import("gpu_frame.zig").logit_rows) return error.BadFrameRows; if (s.head != .none) { var input = f.get(.input); @@ -273,6 +284,10 @@ pub const Stages = struct { head_sums.ref.offset += @as(usize, s.rows - 1) * 4; } try m.kernels.quant(e, m.weights.head, input, head_sums, f.get(.dims), s.logits orelse f.get(.logits), if (s.head == .last) 1 else s.rows); + if (s.hooks.stage) |stage| { + e.barrier(); + try stage(s.hooks.ptr, e, .logits, f.get(.logits), if (s.head == .last) 1 else s.rows); + } } e.barrier(); if (s.reduce) |r| { diff --git a/zig/src/families/qwen27/qwen27.zig b/zig/src/families/qwen27/qwen27.zig index e343776f5f2..e9908680b3e 100644 --- a/zig/src/families/qwen27/qwen27.zig +++ b/zig/src/families/qwen27/qwen27.zig @@ -49,12 +49,16 @@ pub const disk = @import("disk.zig"); pub const taps = @import("taps.zig"); pub const tap_gather = @import("tap_gather.zig"); pub const tap_ring = @import("tap_ring.zig"); +/// Staged references: a round's stage rows copied to their planes (tf-qwen27-run --stages). +pub const stage_planes = @import("stage_planes.zig"); /// The 27B's Metal sources by name (the kernel contract compiles them as the engine does). pub const runtime_sources = @import("qwen_runtime_sources"); test { _ = dflash; _ = disk; _ = @import("core").gpu_profile; + _ = @import("core").qwen35_stages; + _ = stage_planes; _ = session; _ = @import("gdn_test.zig"); _ = @import("simd_attention.zig"); diff --git a/zig/src/families/qwen27/stage_planes.zig b/zig/src/families/qwen27/stage_planes.zig new file mode 100644 index 00000000000..6f14f87f585 --- /dev/null +++ b/zig/src/families/qwen27/stage_planes.zig @@ -0,0 +1,36 @@ +//! Staged references on Metal: a round copies each stage's rows into its own plane, read once the round has run. +const std = @import("std"); +const mtl = @import("metal"); +const Ref = @import("projection.zig").Ref; +const Glue = @import("glue_gpu.zig").Kernels; +const stages = @import("core").qwen35_stages; + +pub const Planes = struct { + buffer: mtl.Buffer, + round: stages.Round, + + pub fn init(device: mtl.Device, recorder: *stages.Recorder, capacity: u32, logit_capacity: u32) !Planes { + const round = try stages.Round.init(recorder, capacity, logit_capacity); + return .{ .buffer = try device.buffer(round.bytes(), mtl.ResourceOptions.shared | mtl.ResourceOptions.untracked), .round = round }; + } + + pub fn deinit(p: Planes) void { + p.buffer.deinit(); + } + + pub fn begin(p: *Planes) void { + p.round.begin(); + } + + pub fn record(p: *Planes, glue: Glue, e: mtl.ComputeEncoder, at: stages.Point, x: Ref, rows: u32) !void { + try p.round.mark(at, rows); + const width: u32 = @intCast(p.round.recorder.width(at)); + try glue.unstack(e, x, .{ .buffer = p.buffer, .offset = p.round.offset(at) }, .{ .rows = rows, .width = width, .stride = width, .offset = 0 }); + e.barrier(); + } + + /// Hands a finished round, whose rows start at cache position `first`, to the recorder. + pub fn end(p: *Planes, first: u32) !void { + try p.round.end(p.buffer.slice(u8, p.buffer.length()), first); + } +}; diff --git a/zig/src/families/qwen3_5/stages.zig b/zig/src/families/qwen3_5/stages.zig new file mode 100644 index 00000000000..86bd3233b80 --- /dev/null +++ b/zig/src/families/qwen3_5/stages.zig @@ -0,0 +1,346 @@ +//! Staged references (off unless asked for): a qwen3_5 forward's stages in one bf16 layout, for qwen36_stage_ref.py. +const std = @import("std"); + +/// The residual stream after the embedding, after each layer's mixer and its MLP, then the final norm and the head. +pub const Point = union(enum) { + embed, + mixer: usize, + block: usize, + final, + logits, + + /// The point's plane among `count(layers)`; a layer past the model's is refused. + pub fn index(p: Point, layers: usize) !usize { + return switch (p) { + .embed => 0, + .mixer => |l| if (l < layers) 1 + 2 * l else error.BadStageLayer, + .block => |l| if (l < layers) 2 + 2 * l else error.BadStageLayer, + .final => 1 + 2 * layers, + .logits => 2 + 2 * layers, + }; + } + + /// The file stem: embed, l07.mixer, l07.block, final, logits. + pub fn name(p: Point, buf: []u8) ![]const u8 { + return switch (p) { + .embed => "embed", + .mixer => |l| std.fmt.bufPrint(buf, "l{d:0>2}.mixer", .{l}), + .block => |l| std.fmt.bufPrint(buf, "l{d:0>2}.block", .{l}), + .final => "final", + .logits => "logits", + }; + } +}; + +pub fn count(layers: usize) usize { + return 3 + 2 * layers; +} + +/// The point at plane `i`, the inverse of `Point.index`. +pub fn point(i: usize, layers: usize) !Point { + if (i >= count(layers)) return error.BadStageLayer; + if (i == 0) return .embed; + if (i == 1 + 2 * layers) return .final; + if (i == 2 + 2 * layers) return .logits; + return if (i % 2 == 1) .{ .mixer = (i - 1) / 2 } else .{ .block = (i - 2) / 2 }; +} + +/// What an engine may record, asked before the round runs: one stream's chain of rows, its final norm and head. +pub fn admit(streams: usize, chain: bool, head: bool) !void { + if (streams != 1) return error.StagesNeedOneStream; + if (!chain) return error.StagesNeedChain; + if (!head) return error.StagesNeedHead; +} + +/// A window whose every row's parent is the row before it (the first's is -1): one linear sequence, no branches. +pub fn isChain(parents: []const i32) bool { + for (parents, 0..) |parent, row| if (parent != @as(i32, @intCast(row)) - 1) return false; + return true; +} + +/// A device engine's stage hook: `rows` rows of the point's width at device address `ptr`, valid once drained. +pub const DeviceHook = struct { + ctx: *anyopaque, + f: *const fn (ctx: *anyopaque, at: Point, ptr: u64, rows: usize) anyerror!void, +}; + +/// One round's planes in an engine's buffer: every stream point `capacity` rows wide, then the logits plane. +pub const Round = struct { + recorder: *Recorder, + capacity: u32, + logit_capacity: u32, + /// Each plane's rows this round: a stream plane left at 0 when the round ends was never recorded. + rows: [max_planes]u32 = @splat(0), + + pub const max_planes = 256; + + pub fn init(recorder: *Recorder, capacity: u32, logit_capacity: u32) !Round { + if (capacity == 0 or logit_capacity == 0 or count(recorder.layers) > max_planes) return error.BadStageShape; + return .{ .recorder = recorder, .capacity = capacity, .logit_capacity = logit_capacity }; + } + + /// The buffer's bytes: every plane at its capacity. + pub fn bytes(r: Round) usize { + return r.offset(.logits) + @as(usize, r.logit_capacity) * r.recorder.vocab * 2; + } + + pub fn offset(r: Round, at: Point) usize { + const i = at.index(r.recorder.layers) catch unreachable; + return i * @as(usize, r.capacity) * r.recorder.hidden * 2; + } + + pub fn begin(r: *Round) void { + r.rows = @splat(0); + } + + /// Claims `at`'s plane for `rows` rows; the engine then copies them to `offset(at)`. + pub fn mark(r: *Round, at: Point, rows: usize) !void { + const i = try at.index(r.recorder.layers); + if (rows == 0 or rows > (if (at == .logits) r.logit_capacity else r.capacity)) return error.BadStageShape; + if (r.rows[i] != 0) return error.DuplicateStage; + r.rows[i] = @intCast(rows); + } + + /// Hands the round in `base` to the recorder (every stream point holds its rows); its marks are spent either way. + pub fn end(r: *Round, base: []const u8, first: u32) !void { + defer r.rows = @splat(0); + const n = count(r.recorder.layers); + if (base.len < r.bytes()) return error.BadStageShape; + const rows = r.rows[0]; + for (r.rows[0..n], 0..) |got, i| if ((try point(i, r.recorder.layers)) != .logits and got != rows) return error.IncompleteStages; + var views: [max_planes][]const u8 = undefined; + for (views[0..n], 0..) |*view, i| { + const at = try point(i, r.recorder.layers); + view.* = base[r.offset(at)..][0 .. @as(usize, r.rows[i]) * r.recorder.width(at) * 2]; + } + try r.recorder.round(first, rows, r.rows[n - 1], views[0..n]); + } +}; + +/// A run's stages on the host: bf16 rows per point and the cache position of every row, in the order rounds ran. +pub const Recorder = struct { + allocator: std.mem.Allocator, + layers: usize, + hidden: usize, + vocab: usize, + planes: []std.ArrayList(u8), + positions: std.ArrayList(u32) = .empty, + logit_positions: std.ArrayList(u32) = .empty, + + pub fn init(a: std.mem.Allocator, layers: usize, hidden: usize, vocab: usize) !Recorder { + if (layers == 0 or hidden == 0 or vocab == 0) return error.BadStageShape; + const planes = try a.alloc(std.ArrayList(u8), count(layers)); + @memset(planes, .empty); + return .{ .allocator = a, .layers = layers, .hidden = hidden, .vocab = vocab, .planes = planes }; + } + + pub fn deinit(r: *Recorder) void { + for (r.planes) |*p| p.deinit(r.allocator); + r.allocator.free(r.planes); + r.positions.deinit(r.allocator); + r.logit_positions.deinit(r.allocator); + } + + pub fn width(r: Recorder, p: Point) usize { + return if (p == .logits) r.vocab else r.hidden; + } + + /// One round from cache position `first`, all or nothing; `logits` rows end at its last (0, 1 or `rows`). + pub fn round(r: *Recorder, first: u32, rows: u32, logits: u32, planes: []const []const u8) !void { + if (rows == 0 or (logits != 0 and logits != 1 and logits != rows) or planes.len != count(r.layers)) return error.BadStageShape; + for (planes, 0..) |bytes, i| { + const p = try point(i, r.layers); + const n: usize = if (p == .logits) logits else rows; + if (bytes.len != n * r.width(p) * 2) return error.BadStageShape; + } + for (planes, r.planes) |bytes, *plane| try plane.ensureUnusedCapacity(r.allocator, bytes.len); + try r.positions.ensureUnusedCapacity(r.allocator, rows); + try r.logit_positions.ensureUnusedCapacity(r.allocator, logits); + for (planes, r.planes) |bytes, *plane| plane.appendSliceAssumeCapacity(bytes); + for (0..rows) |row| r.positions.appendAssumeCapacity(first + @as(u32, @intCast(row))); + for (rows - logits..rows) |row| r.logit_positions.appendAssumeCapacity(first + @as(u32, @intCast(row))); + } + + /// `dir`/.bf16 per point, row-major, and index.json with the shapes and every row's cache position. + pub fn write(r: Recorder, io: std.Io, dir: []const u8) !void { + const cwd = std.Io.Dir.cwd(); + try cwd.createDirPath(io, dir); + var path_buf: [std.fs.max_path_bytes]u8 = undefined; + var name_buf: [32]u8 = undefined; + const Entry = struct { name: []const u8, width: usize, rows: usize }; + const entries = try r.allocator.alloc(Entry, r.planes.len); + defer r.allocator.free(entries); + for (r.planes, entries, 0..) |plane, *entry, i| { + const p = try point(i, r.layers); + const stem = try p.name(&name_buf); + const path = try std.fmt.bufPrint(&path_buf, "{s}/{s}.bf16", .{ dir, stem }); + try cwd.writeFile(io, .{ .sub_path = path, .data = plane.items }); + entry.* = .{ .name = try r.allocator.dupe(u8, stem), .width = r.width(p), .rows = plane.items.len / (r.width(p) * 2) }; + } + defer for (entries) |e| r.allocator.free(e.name); + const index = try std.json.Stringify.valueAlloc(r.allocator, .{ + .version = 1, + .dtype = "bf16", + .layers = r.layers, + .hidden = r.hidden, + .vocab = r.vocab, + .stages = entries, + .positions = r.positions.items, + .logit_positions = r.logit_positions.items, + }, .{}); + defer r.allocator.free(index); + try cwd.writeFile(io, .{ .sub_path = try std.fmt.bufPrint(&path_buf, "{s}/index.json", .{dir}), .data = index }); + } +}; + +test "stage planes and names cover every point once, in forward order" { + var buf: [32]u8 = undefined; + for ([_]usize{ 1, 2, 40 }) |layers| { + for (0..count(layers)) |i| try std.testing.expectEqual(i, try (try point(i, layers)).index(layers)); + } + try std.testing.expectEqualStrings("l07.mixer", try (Point{ .mixer = 7 }).name(&buf)); + try std.testing.expectEqualStrings("l39.block", try (Point{ .block = 39 }).name(&buf)); + try std.testing.expectError(error.BadStageLayer, (Point{ .block = 2 }).index(2)); + try std.testing.expectError(error.BadStageLayer, point(count(2), 2)); +} + +test "isChain and admit: every parent list of up to three rows, stream count and head" { + const choices = [_]i32{ -2, -1, 0, 1, 2 }; + var parents: [3]i32 = undefined; + for (0..4) |len| for (0..std.math.pow(usize, choices.len, len)) |code| { + var c = code; + for (parents[0..len]) |*p| { + p.* = choices[c % choices.len]; + c /= choices.len; + } + const chain = [_]i32{ -1, 0, 1 }; + try std.testing.expectEqual(std.mem.eql(i32, chain[0..len], parents[0..len]), isChain(parents[0..len])); + }; + for (0..3) |streams| for ([_]bool{ false, true }) |chain| for ([_]bool{ false, true }) |head| { + const want: ?anyerror = if (streams != 1) error.StagesNeedOneStream else if (!chain) error.StagesNeedChain else if (!head) error.StagesNeedHead else null; + if (want) |err| try std.testing.expectError(err, admit(streams, chain, head)) else try admit(streams, chain, head); + }; +} + +test "Round: every sequence of four round events lands exactly the rounds a model of the engine's caller lands" { + // One layer, one value wide, 2 rows of capacity; fill tags every point's rows, partial only the embedding's. + const Fill = struct { rows: u32, head: u32 }; + const Event = union(enum) { begin, fill: Fill, partial, end, fail: usize }; + const events = [_]Event{ + .begin, .partial, .end, + .{ .fill = .{ .rows = 1, .head = 0 } }, .{ .fill = .{ .rows = 1, .head = 1 } }, .{ .fill = .{ .rows = 1, .head = 2 } }, + .{ .fill = .{ .rows = 2, .head = 0 } }, .{ .fill = .{ .rows = 2, .head = 1 } }, .{ .fill = .{ .rows = 2, .head = 2 } }, + .{ .fail = 0 }, .{ .fail = 3 }, .{ .fail = 6 }, + }; + const a = std.testing.allocator; + const n = events.len + 1; + var seq: [4]usize = undefined; + var landed_rounds: usize = 0; + var refused_by_oom: usize = 0; + for (0..std.math.pow(usize, n, seq.len)) |code| { + var c = code; + var len: usize = 0; + while (len < seq.len and c % n != events.len) : (len += 1) { + seq[len] = c % n; + c /= n; + } + if (len < seq.len and c / n != 0) continue; // events after the end marker would repeat a shorter sequence + var failing = std.testing.FailingAllocator.init(a, .{}); + var rec = try Recorder.init(failing.allocator(), 1, 1, 1); + defer rec.deinit(); + var round_ = try Round.init(&rec, 2, 2); + var base: [64]u8 = @splat(0); + // The model: what is marked, every plane's bytes and the positions that should have landed. + var marked: enum { none, partial, fill } = .none; + var fill: Fill = undefined; + var tag: u8 = 0; + var next: u32 = 9; + var want: [5]std.ArrayList(u8) = @splat(.empty); + defer for (&want) |*w| w.deinit(a); + var want_positions: std.ArrayList(u32) = .empty; + defer want_positions.deinit(a); + var want_logits: std.ArrayList(u32) = .empty; + defer want_logits.deinit(a); + for (seq[0..len]) |e| switch (events[e]) { + .begin => { + round_.begin(); + marked = .none; + }, + .partial => { + const got = round_.mark(.embed, 1); + if (marked == .none) { + try got; + marked = .partial; + } else try std.testing.expectError(error.DuplicateStage, got); + }, + .fill => |f| { + // The engine's order: a refused mark stops the forward, so a fill lands whole or not at all. + if (marked != .none) { + try std.testing.expectError(error.DuplicateStage, round_.mark(.embed, f.rows)); + continue; + } + tag += 1; + for (0..5) |i| { + const at = try point(i, 1); + const rows = if (at == .logits) f.head else f.rows; + if (rows == 0) continue; + try round_.mark(at, rows); + @memset(base[round_.offset(at)..][0 .. rows * 2], tag); + } + marked = .fill; + fill = f; + }, + .end, .fail => { + const k: ?usize = if (events[e] == .fail) events[e].fail else null; + if (k) |after| { + failing.fail_index = failing.alloc_index + after; + failing.resize_fail_index = failing.resize_index + after; + } + const got = round_.end(&base, next); + failing.fail_index = std.math.maxInt(usize); + failing.resize_fail_index = std.math.maxInt(usize); + const was = marked; + marked = .none; + switch (was) { + .none => try std.testing.expectError(error.BadStageShape, got), + .partial => try std.testing.expectError(error.IncompleteStages, got), + .fill => if (fill.head == 2 and fill.rows == 1) try std.testing.expectError(error.BadStageShape, got) else { + got catch |err| { + try std.testing.expect(k != null and err == error.OutOfMemory); + refused_by_oom += 1; + continue; + }; + landed_rounds += 1; + for (&want, 0..) |*w, i| try w.appendNTimes(a, tag, 2 * if (i == 4) fill.head else fill.rows); + for (0..fill.rows) |row| try want_positions.append(a, next + @as(u32, @intCast(row))); + for (fill.rows - fill.head..fill.rows) |row| try want_logits.append(a, next + @as(u32, @intCast(row))); + next += fill.rows; + }, + } + }, + }; + for (want, rec.planes) |w, got| try std.testing.expectEqualSlices(u8, w.items, got.items); + try std.testing.expectEqualSlices(u32, want_positions.items, rec.positions.items); + try std.testing.expectEqualSlices(u32, want_logits.items, rec.logit_positions.items); + } + // The enumeration reaches both a landed round and an allocation failure that leaves the recorder unchanged. + try std.testing.expect(landed_rounds > 0 and refused_by_oom > 0); +} + +test "a round's rows land on their positions; a short plane or odd head count is refused" { + const a = std.testing.allocator; + var r = try Recorder.init(a, 1, 2, 3); + defer r.deinit(); + const row: [4]u8 = @splat(0); + const two: [8]u8 = @splat(0); + const logit: [6]u8 = @splat(0); + // A two-row prompt round with its last row's logits, then a one-row step. + try r.round(5, 2, 1, &.{ &two, &two, &two, &two, &logit }); + try r.round(7, 1, 1, &.{ &row, &row, &row, &row, &logit }); + try std.testing.expectEqualSlices(u32, &.{ 5, 6, 7 }, r.positions.items); + try std.testing.expectEqualSlices(u32, &.{ 6, 7 }, r.logit_positions.items); + try std.testing.expectEqual(@as(usize, 12), r.planes[0].items.len); + try std.testing.expectError(error.BadStageShape, r.round(8, 1, 1, &.{ &row, &row, &row, row[0..2], &logit })); + try std.testing.expectError(error.BadStageShape, r.round(8, 3, 2, &.{ &row, &row, &row, &row, &logit })); + try std.testing.expectEqual(@as(usize, 3), r.positions.items.len); +} diff --git a/zig/tests/qwen27/run.zig b/zig/tests/qwen27/run.zig index 46420bb9e1b..fe48aa651e3 100644 --- a/zig/tests/qwen27/run.zig +++ b/zig/tests/qwen27/run.zig @@ -4,13 +4,15 @@ const q = @import("qwen27"); const mtl = @import("metal"); const sources = @import("qwen_runtime_sources"); const gdn_source = @import("qwen_gdn_source"); -const profile = @import("core").gpu_profile; +const core = @import("core"); +const profile = core.gpu_profile; const core_lane = @import("core_lane"); const help = \\tf-qwen27-run --run --model DIR --tokens IDS.json [--max-tokens 256] \\ [--chunk 128] [--compare-chunk 16] [--reference GENERATED.json] [--force-length] \\ [--no-warmup] [--profile-steps N] [--profile-prompt] [--teacher] [--seams N] [--resume-reply] + \\ [--stages DIR] \\IDs and reference files are JSON arrays of unsigned token IDs, already chat-rendered. \\Greedy only, drafts off; JSON receipt on stdout, errors on stderr. \\--teacher feeds every reference token and records native top2 at all positions; margin timing is diagnostic. @@ -19,6 +21,7 @@ const help = \\--seams N (with --compare-chunk): state/KV/logits bytes every N prompt rows under both chunks and after decode. \\--resume-reply: the reply fed again in one pass that keeps no row, then a turn's tail, against decoding it. \\--profile-prompt: GPU seconds by class over the timed prompt (split command buffers, so slower than unprofiled). + \\--stages DIR writes the measured prompt's and decode's staged references (stream per stage, final norm, logits). \\CPU only: --help or --emit-sources EXISTING_DIR, no Metal device or model load. ; @@ -110,6 +113,7 @@ pub fn main(init: std.process.Init) !void { var chunk: usize = 128; var compare: usize = 0; var seam_every: usize = 0; + var stages_dir: ?[]const u8 = null; var run = false; var force = false; var warmup = true; @@ -146,7 +150,7 @@ pub fn main(init: std.process.Init) !void { if (i + 1 >= args.len) return error.MissingValue; i += 1; const value = args[i]; - if (std.mem.eql(u8, arg, "--model")) model = value else if (std.mem.eql(u8, arg, "--tokens")) file = value else if (std.mem.eql(u8, arg, "--reference")) reference = value else if (std.mem.eql(u8, arg, "--max-tokens")) count = try std.fmt.parseInt(usize, value, 10) else if (std.mem.eql(u8, arg, "--chunk")) chunk = try std.fmt.parseInt(usize, value, 10) else if (std.mem.eql(u8, arg, "--profile-steps")) profile_steps = try std.fmt.parseInt(usize, value, 10) else if (std.mem.eql(u8, arg, "--compare-chunk")) compare = try std.fmt.parseInt(usize, value, 10) else if (std.mem.eql(u8, arg, "--seams")) seam_every = try std.fmt.parseInt(usize, value, 10) else return error.UnknownOption; + if (std.mem.eql(u8, arg, "--model")) model = value else if (std.mem.eql(u8, arg, "--tokens")) file = value else if (std.mem.eql(u8, arg, "--reference")) reference = value else if (std.mem.eql(u8, arg, "--max-tokens")) count = try std.fmt.parseInt(usize, value, 10) else if (std.mem.eql(u8, arg, "--chunk")) chunk = try std.fmt.parseInt(usize, value, 10) else if (std.mem.eql(u8, arg, "--profile-steps")) profile_steps = try std.fmt.parseInt(usize, value, 10) else if (std.mem.eql(u8, arg, "--compare-chunk")) compare = try std.fmt.parseInt(usize, value, 10) else if (std.mem.eql(u8, arg, "--seams")) seam_every = try std.fmt.parseInt(usize, value, 10) else if (std.mem.eql(u8, arg, "--stages")) stages_dir = value else return error.UnknownOption; } if (!run or model == null or file == null or chunk == 0 or chunk > 2048 or compare > 2048 or count > 65536 or (seam_every > 0 and compare == 0)) return error.BadOptions; const ids = try tokens(a, io, file.?); @@ -174,6 +178,15 @@ pub fn main(init: std.process.Init) !void { var trace = profile.Trace{ .queue = m.queue }; if (profile_steps > 0 or profile_prompt) runner.profile(&trace); trace.enabled = profile_prompt; + var recorder: ?core.qwen35_stages.Recorder = null; + defer if (recorder) |*r| r.deinit(); + var planes: ?q.stage_planes.Planes = null; + defer if (planes) |p| p.deinit(); + if (stages_dir != null) { + recorder = try core.qwen35_stages.Recorder.init(init.gpa, m.config.layers, m.config.hidden, m.config.vocab); + planes = try q.stage_planes.Planes.init(m.device, &recorder.?, m.frame.capacity, @min(m.frame.capacity, q.gpu_frame.logit_rows)); + runner.stages = &planes.?; + } const start = std.Io.Clock.awake.now(io); try s.prefill(ids, chunk); const prompt_ns = start.durationTo(std.Io.Clock.awake.now(io)).toNanoseconds(); @@ -183,6 +196,8 @@ pub fn main(init: std.process.Init) !void { const generation = try generated(a, s, count, force, expected, if (profile_steps > 0) &trace else null, profile_steps, teacher); const out = generation.tokens; const decode_ns = decode_start.durationTo(std.Io.Clock.awake.now(io)).toNanoseconds(); + runner.stages = null; + if (stages_dir) |dir| try recorder.?.write(io, dir); const decoded = if (compare > 0) try s.fingerprint() else digest; const reference_equal = if (expected) |wanted| std.mem.eql(u32, out, wanted) else false; if (compare > 0) { From 73117422e287bca1d3e99488313c50eccb60c131 Mon Sep 17 00:00:00 2001 From: Shinto C V <11365900+cshintov@users.noreply.github.com> Date: Fri, 6 Nov 2026 08:12:40 +0530 Subject: [PATCH 06/13] qwen27: staged references take a headless prompt chunk (0 logit rows), as the recorder allows While stages record, the last layer counts as tapped, so main's keys-only last layer stays off and the recorded stream and final are real rows. The stage hook (planes and glue) and the admit check move into stage_planes.zig, so the runner needs no forwarding function, and planes.end runs after the round is committed, so a recorder error leaves the runner consistent. --- zig/src/families/qwen27/decode_round.zig | 20 ++++++-------------- zig/src/families/qwen27/forward.zig | 15 +++++++-------- zig/src/families/qwen27/stage_planes.zig | 15 +++++++++++++++ 3 files changed, 28 insertions(+), 22 deletions(-) diff --git a/zig/src/families/qwen27/decode_round.zig b/zig/src/families/qwen27/decode_round.zig index 1b2884944b4..53ebe63692b 100644 --- a/zig/src/families/qwen27/decode_round.zig +++ b/zig/src/families/qwen27/decode_round.zig @@ -30,7 +30,7 @@ const kv_slots = @import("kv_slots.zig"); /// The host's hook for buffers a slot's K/V growth made. pub const Grown = struct { ctx: *anyopaque, added: *const fn (ctx: *anyopaque, buffers: []const mtl.Buffer) void }; -const staged = @import("core").qwen35_stages; +const stage_planes = @import("stage_planes.zig"); /// Whether `cb` failed on the GPU; its Metal error (out of memory, a timeout) is logged with `what` it ran. pub fn gpuFailed(cb: mtl.CommandBuffer, what: []const u8) bool { const msg = cb.failure() orelse return false; @@ -284,8 +284,7 @@ pub const Runner = struct { // A rank's head writes only this rank's vocabulary columns; the tail's matcher reads the whole vocabulary. if (r.tail != null and r.reduce != null) return error.TailOnRank; for (round.slots, round.windows) |slot, window| if (slot >= r.ready or r.offsets[slot] != window.start) return error.CachePositionDiffers; - // staged references record one stream's chain with its head: refused before the round touches any state - if (r.stages != null) try staged.admit(round.windows.len, round.windows.len == 1 and staged.isChain(round.windows[0].parents), head != .none); + if (r.stages != null) try stage_planes.admit(round.windows); // refused before the round touches any state for (round.slots, round.windows) |slot, window| try r.cover(slot, window.start + @as(u32, @intCast(window.parents.len))); for (round.slots, round.windows) |slot, window| try r.reserve(slot, window.start + @as(u32, @intCast(window.parents.len))); const paths = try r.allocator.alloc([]const u32, round.windows.len); @@ -332,12 +331,13 @@ pub const Runner = struct { defer pool.pop(); const spanned = if (r.trace) |t| t.spanned else 0; // a profiled pass's spans commit buffers of their own const handed = if (r.model.ane) |share| share.gpu_seconds else 0; - const tail_facts = @import("prompt_tail.zig").facts(r, head, accepted, placed.images != null or r.images != null); + var tail_facts = @import("prompt_tail.zig").facts(r, head, accepted, placed.images != null or r.images != null); + tail_facts.last_tapped = tail_facts.last_tapped or r.stages != null; // staged references read the last layer's rows r.tail_from = @import("prompt_tail.zig").first(tail_facts, round.ids.len, round.windows.len); defer r.tail_from = null; if (r.tail_from) |t0| r.model.frame.setTail(t0, @intCast(round.ids.len)); const keys = @import("prompt_tail.zig").keysOnly(tail_facts); - var stages = forward.Stages{ .model = r.model, .rows = @intCast(round.ids.len), .hooks = .{ .ptr = r, .gdn = gdnForward, .attention = attentionForward, .tap = if (r.capture_taps) tap else null, .keys = if (keys) prompt_tail.keysForward else null, .stage = if (r.stages != null) stage else null }, .head = head, .tail = r.tail, .images = placed.images, .reduce = r.reduce, .picks = r.picks, .tail_from = r.tail_from }; + var stages = forward.Stages{ .model = r.model, .rows = @intCast(round.ids.len), .hooks = .{ .ptr = r, .gdn = gdnForward, .attention = attentionForward, .tap = if (r.capture_taps) tap else null, .keys = if (keys) prompt_tail.keysForward else null, .stage = if (r.stages) |p| .{ .planes = p, .glue = r.model.glue } else null }, .head = head, .tail = r.tail, .images = placed.images, .reduce = r.reduce, .picks = r.picks, .tail_from = r.tail_from }; r.last_gpu_seconds = @import("core").segments.runCommitting(r.model.device, &.{r.model.queue}, r.model.config.layers, .concurrent, &stages, commit_every) catch |err| { r.failed = true; return err; @@ -359,13 +359,10 @@ pub const Runner = struct { try r.taps.complete(); for (round.slots, round.windows, round.firsts) |slot, w, first| r.tapped[slot] = .{ .start = w.start, .first = first, .rows = @intCast(w.parents.len) }; } - if (r.stages) |planes| planes.end(round.windows[0].start) catch |err| { - r.failed = true; - return err; - }; if (accepted) { for (round.slots, round.windows) |slot, window| r.offsets[slot] = window.start + @as(u32, @intCast(window.parents.len)); } else r.active = fingerprint(round); + if (r.stages) |planes| try planes.end(round.windows[0].start); // after the round is committed, so a refusal leaves it whole } /// One MTP head pass (mtp.zig `pass`); a round left to keep reads nothing it writes. @@ -582,11 +579,6 @@ pub const Runner = struct { const r: *Runner = @ptrCast(@alignCast(ptr)); try r.taps.record(r.model.glue, e, layer, hidden, rows); } - - fn stage(ptr: *anyopaque, e: mtl.ComputeEncoder, at: forward.Point, x: @import("projection.zig").Ref, rows: u32) !void { - const r: *Runner = @ptrCast(@alignCast(ptr)); - try r.stages.?.record(r.model.glue, e, at, x, rows); - } }; fn fingerprint(round: *const Round) [32]u8 { diff --git a/zig/src/families/qwen27/forward.zig b/zig/src/families/qwen27/forward.zig index c698cfa10f1..beb7b49372a 100644 --- a/zig/src/families/qwen27/forward.zig +++ b/zig/src/families/qwen27/forward.zig @@ -17,9 +17,8 @@ pub const Mixer = struct { /// A pass that keeps no row and has no other reader of the last layer: that layer writes keys and values only. keys: ?*const fn (*anyopaque, mtl.ComputeEncoder, usize, wts.Attention, *Frame, u32) anyerror!void = null, /// Staged references (off unless asked for): the stream after each stage, the final norm and the head's rows. - stage: ?*const fn (*anyopaque, mtl.ComputeEncoder, Point, Ref, u32) anyerror!void = null, + stage: ?@import("stage_planes.zig").Hook = null, }; -pub const Point = @import("core").qwen35_stages.Point; /// One exchange: `x` its index, `ref` this rank's `width` columns of the seam in the window's slot for x. pub const Seam = struct { x: u32, ref: Ref }; @@ -104,7 +103,7 @@ pub const Stages = struct { m.glue.imageRows(lane.enc, s.hidden, rows, m.frame.get(.takes), @intCast(m.config.hidden), s.rows); lane.enc.barrier(); } - if (s.hooks.stage) |stage| try stage(s.hooks.ptr, lane.enc, .embed, s.hidden, s.rows); + if (s.hooks.stage) |stage| try stage.record(lane.enc, .embed, s.hidden, s.rows); } pub fn wait(_: *Stages, _: usize) @import("core").segments.Wait { return .mixer; @@ -121,7 +120,7 @@ pub const Stages = struct { if (s.pending != null) { std.mem.swap(Ref, &s.hidden, &s.residual); if (s.hooks.tap) |tap| try tap(s.hooks.ptr, e, index - 1, s.hidden, s.rows); - if (s.hooks.stage) |stage| try stage(s.hooks.ptr, e, .{ .block = index - 1 }, s.hidden, s.rows); + if (s.hooks.stage) |stage| try stage.record(e, .{ .block = index - 1 }, s.hidden, s.rows); } } /// The last layer of a pass whose other rows nothing reads: q, attention, o and the MLP have no reader. @@ -178,7 +177,7 @@ pub const Stages = struct { try m.kernels.norm(e, t.at(s.hidden, h), t.at(f.get(.output), h), wts.ref(layer.post_norm), f.get(.eps), t.dims, t.at(s.residual, h), t.at(f.get(.input), h), t.sums(f.get(.sums)), h, t.n); e.barrier(); std.mem.swap(Ref, &s.hidden, &s.residual); - if (s.hooks.stage) |stage| try stage(s.hooks.ptr, e, .{ .mixer = index }, s.hidden, s.rows); + if (s.hooks.stage) |stage| try stage.record(e, .{ .mixer = index }, s.hidden, s.rows); if (layer.moe) |*mo| if (!m.moe.?.sorted(mo, m.kernels.prompt)) { // decode rows: the routed block runs the shared expert as one more slot of the experts' kernel try m.moe.?.block(lane.enc, m.config, mo, f, s.rows, m.kernels.prompt); @@ -272,8 +271,8 @@ pub const Stages = struct { if (s.hooks.tap) |tap| try tap(s.hooks.ptr, e, m.config.layers - 1, s.hidden, s.rows); if (s.hooks.stage) |stage| { // the last block is the residual stream; final is the normed rows the head reads (f.input) - try stage(s.hooks.ptr, e, .{ .block = m.config.layers - 1 }, s.hidden, s.rows); - try stage(s.hooks.ptr, e, .final, f.get(.input), s.rows); + try stage.record(e, .{ .block = m.config.layers - 1 }, s.hidden, s.rows); + try stage.record(e, .final, f.get(.input), s.rows); } if (s.head == .all and s.rows > @import("gpu_frame.zig").logit_rows) return error.BadFrameRows; if (s.head != .none) { @@ -286,7 +285,7 @@ pub const Stages = struct { try m.kernels.quant(e, m.weights.head, input, head_sums, f.get(.dims), s.logits orelse f.get(.logits), if (s.head == .last) 1 else s.rows); if (s.hooks.stage) |stage| { e.barrier(); - try stage(s.hooks.ptr, e, .logits, f.get(.logits), if (s.head == .last) 1 else s.rows); + try stage.record(e, .logits, f.get(.logits), if (s.head == .last) 1 else s.rows); } } e.barrier(); diff --git a/zig/src/families/qwen27/stage_planes.zig b/zig/src/families/qwen27/stage_planes.zig index 6f14f87f585..c7bae7eb168 100644 --- a/zig/src/families/qwen27/stage_planes.zig +++ b/zig/src/families/qwen27/stage_planes.zig @@ -34,3 +34,18 @@ pub const Planes = struct { try p.round.end(p.buffer.slice(u8, p.buffer.length()), first); } }; + +/// Staged references record one stream's chain (a headless prompt chunk records 0 logit rows); others are refused. +pub fn admit(windows: anytype) !void { + try stages.admit(windows.len, windows.len == 1 and stages.isChain(windows[0].parents), true); +} + +/// The forward pass's stage hook: each stage's rows into `planes` through the model's glue. +pub const Hook = struct { + planes: *Planes, + glue: Glue, + + pub fn record(h: Hook, e: mtl.ComputeEncoder, at: stages.Point, x: Ref, rows: u32) !void { + try h.planes.record(h.glue, e, at, x, rows); + } +}; From 3544918677d335f10cd0ae8653db780af1b8faec Mon Sep 17 00:00:00 2001 From: Shinto C V <11365900+cshintov@users.noreply.github.com> Date: Fri, 6 Nov 2026 08:25:24 +0530 Subject: [PATCH 07/13] contract: qwen27 attention's decode and prompt rows at the 35B-A3B's 16 query heads over 2 --- zig/tests/contract/metal_q27_attn.zig | 6 ++++-- zig/tests/contract/metal_q27_attn_rows.zig | 2 +- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/zig/tests/contract/metal_q27_attn.zig b/zig/tests/contract/metal_q27_attn.zig index f5649ac014a..7b27a72cff2 100644 --- a/zig/tests/contract/metal_q27_attn.zig +++ b/zig/tests/contract/metal_q27_attn.zig @@ -12,8 +12,8 @@ const planning = q.attention_plan; const D = 256; -/// Geometry.check's shapes: the 27B (24 over 4), its two-Mac rank (12 over 2), GQA16 (32 over 2), the 9B (16 over 4). -pub const Heads = enum { q27b, rank, gqa16, q9b }; +/// Geometry.check's shapes: the 27B (24/4), its two-Mac rank (12/2), GQA16 (32/2), the 9B (16/4), the 35B-A3B (16/2). +pub const Heads = enum { q27b, rank, gqa16, q9b, q35b }; pub fn geometry(h: Heads, shared: bool) planning.Geometry { return switch (h) { @@ -21,6 +21,7 @@ pub fn geometry(h: Heads, shared: bool) planning.Geometry { .rank => .{ .heads = 12, .kv_heads = 2, .shared_prefix = shared }, .gqa16 => .{ .heads = 32, .kv_heads = 2, .shared_prefix = shared }, .q9b => .{ .heads = 16, .kv_heads = 4, .shared_prefix = shared }, + .q35b => .{ .heads = 16, .kv_heads = 2, .shared_prefix = shared }, }; } @@ -30,6 +31,7 @@ pub fn label(h: Heads) []const u8 { .rank => "27B rank", .gqa16 => "GQA16", .q9b => "9B", + .q35b => "35B-A3B", }; } diff --git a/zig/tests/contract/metal_q27_attn_rows.zig b/zig/tests/contract/metal_q27_attn_rows.zig index 613f4470db1..5ba3f49c74e 100644 --- a/zig/tests/contract/metal_q27_attn_rows.zig +++ b/zig/tests/contract/metal_q27_attn_rows.zig @@ -19,7 +19,7 @@ const u = 0x1p-24; const scale = 0.0625; /// One Mac's head counts (a rank's 12 over 2 merges as a pair, so its rows are not one call's). -pub const heads = [_]at_.Heads{ .q27b, .gqa16, .q9b }; +pub const heads = [_]at_.Heads{ .q27b, .gqa16, .q9b, .q35b }; /// decode: a round's trees and chains as decode_round.zig plans them; prompt: one chain through the prompt kernel. pub const Which = enum { decode, prompt }; From 346472482477a4aa9a63690a6bb6e31b63c9f882 Mon Sep 17 00:00:00 2001 From: Shinto C V <11365900+cshintov@users.noreply.github.com> Date: Sat, 14 Nov 2026 15:42:17 +0530 Subject: [PATCH 08/13] core: export qwen35_stages for the qwen27 stage recorder --- zig/src/tensorfold.zig | 1 + 1 file changed, 1 insertion(+) diff --git a/zig/src/tensorfold.zig b/zig/src/tensorfold.zig index f7b358c5d90..fb87af6985f 100644 --- a/zig/src/tensorfold.zig +++ b/zig/src/tensorfold.zig @@ -74,6 +74,7 @@ pub const flashnext_learned = @import("families/flashnext/learned.zig"); pub const flashnext_think_check = @import("families/flashnext/think_check.zig"); pub const glm = @import("families/glm/glm.zig"); pub const qwen35 = @import("families/qwen3_5/qwen3_5.zig"); +pub const qwen35_stages = @import("families/qwen3_5/stages.zig"); pub const gemma4 = @import("families/gemma4/gemma4.zig"); pub const step5 = @import("families/step5/step5.zig"); pub const spark25_metal = @import("families/spark25/metal.zig"); From dc0f4b43bb86b2781ac53a00961176cba2296af7 Mon Sep 17 00:00:00 2001 From: Shinto C V <11365900+cshintov@users.noreply.github.com> Date: Mon, 16 Nov 2026 13:24:32 +0530 Subject: [PATCH 09/13] Qwen3.5 host tables: the 35B-A3B's row; stage_ref test skips without mlx The A3B config in qwen27/config_test.zig is a new real config: Metal's 27B and HIP admit it, as main's rules did; the 2B, CUDA and XPU keep their refusal. The stage reference test needs mlx, which CI does not install. --- tools/zig/qwen36_stage_ref_test.py | 7 +++++-- zig/qwen35_layers_host.zig | 29 +++++++++++++++++++++++++++-- zig/qwen35_rules_host.zig | 22 +++++++++++++++++++++- 3 files changed, 53 insertions(+), 5 deletions(-) diff --git a/tools/zig/qwen36_stage_ref_test.py b/tools/zig/qwen36_stage_ref_test.py index 040d9c7e679..c383fb07d33 100644 --- a/tools/zig/qwen36_stage_ref_test.py +++ b/tools/zig/qwen36_stage_ref_test.py @@ -4,9 +4,12 @@ import unittest from pathlib import Path -import mlx.core as mx +try: + import mlx.core as mx + from mlx_lm.models.gated_delta import gated_delta_ops +except ImportError: + raise unittest.SkipTest("mlx and mlx_lm are not installed") import numpy as np -from mlx_lm.models.gated_delta import gated_delta_ops from qwen36_f64 import Checkpoint, Model, delta_rule, rms from qwen36_stage_ref import Dump, bf16, measure, stage_names, step diff --git a/zig/qwen35_layers_host.zig b/zig/qwen35_layers_host.zig index b55030b5723..90e5047f6e4 100644 --- a/zig/qwen35_layers_host.zig +++ b/zig/qwen35_layers_host.zig @@ -179,7 +179,7 @@ const sources = .{ .{ "src/families/qwen3_5/cuda_modelopt.zig", 1 }, .{ "src/families/qwen3_5/cuda_quant_admission_test.zig", 1 }, .{ "src/families/qwen3_5/pocket_shards_test.zig", 1 }, - .{ "src/families/qwen27/config_test.zig", 2 }, // with #1125's Ornith-1.5-122B (qwen3_5_moe) + .{ "src/families/qwen27/config_test.zig", 3 }, // with #1125's Ornith-1.5-122B and Qwen3.6-35B-A3B (qwen3_5_moe) .{ "src/families/qwen27/weights_test.zig", 1 }, .{ "qwen35_formats_host.zig", 1 }, }; @@ -248,6 +248,31 @@ fn config(a: std.mem.Allocator, file: []const u8, text: []const u8) !?Real { return .{ .file = file, .json = try a.dupe(u8, text), .tower = tower, .layers = @intCast(n.integer) }; } +/// Qwen3.6-35B-A3B's config (qwen27/config_test.zig's `a3b_json`): 40 layers over a 2,048 hidden width. +pub fn a3b(a: std.mem.Allocator) !Real { + for (try reals(a)) |r| if (r.layers == 40 and r.tower.get("hidden_size").?.integer == 2048) return r; + return error.NoA3bConfig; +} + +test "qwen35 layers: Qwen3.6-35B-A3B, every fourth of 40 through Metal's 27B and HIP, refused by the others" { + var arena: std.heap.ArenaAllocator = .init(t.allocator); + defer arena.deinit(); + const r = try a3b(arena.allocator()); + const want = std.EnumArray(Backend, Outcome).init(.{ + .metal27 = .every(4, 40), + .hip = .every(4, 40), + .metal2b = .{ .refused = error.UnsupportedQwenConfig }, + .cuda = .{ .refused = error.UnsupportedActivation }, + .xpu = .{ .refused = error.UnsupportedQwenShape }, + }); + for (std.enums.values(Backend)) |b| { + const now = entry(b, r.json); + errdefer std.debug.print("{s}: {any}\n", .{ @tagName(b), now }); + const w = want.get(b); + if (w == .pattern) try t.expect(Outcome.same(w, now)) else try t.expect(now == .refused and now.refused == w.refused); + } +} + test "qwen35 layers: real configs, each entry point admits the pattern its old rule read, by the shared reader" { var arena: std.heap.ArenaAllocator = .init(t.allocator); defer arena.deinit(); @@ -267,7 +292,7 @@ test "qwen35 layers: real configs, each entry point admits the pattern its old r relaxed += @intFromBool(now == .pattern and was == .refused); } } - try t.expectEqual(@as(usize, 21), admitted); // (config, backend) pairs, with #2046's and LightOnOCR-3's HIP BF16 and #1125's Ornith + try t.expectEqual(@as(usize, 23), admitted); // (config, backend) pairs, with #2046's and LightOnOCR-3's HIP BF16, #1125's Ornith and the 35B-A3B try t.expectEqual(@as(usize, 0), relaxed); // none of the repo's configs is one the table newly admits } diff --git a/zig/qwen35_rules_host.zig b/zig/qwen35_rules_host.zig index 725dcb4541b..b001091c24c 100644 --- a/zig/qwen35_rules_host.zig +++ b/zig/qwen35_rules_host.zig @@ -108,7 +108,27 @@ test "qwen35 rules: real configs, each entry point admits what main admitted, an try t.expectEqual(was, now); admitted += @intFromBool(now); }; - try t.expectEqual(@as(usize, 44), admitted); // (config, backend) pairs whose tower passes the rows + try t.expectEqual(@as(usize, 46), admitted); // (config, backend) pairs whose tower passes the rows, the 35B-A3B's two with them +} + +test "qwen35 rules: Qwen3.6-35B-A3B, admitted by Metal's 27B and HIP as on main, the others keep their refusal" { + var arena: std.heap.ArenaAllocator = .init(t.allocator); + defer arena.deinit(); + const r = try layers_host.a3b(arena.allocator()); + // no hidden_act: CUDA and the 2B require it, Metal's 27B and HIP read it only when present + const want = std.EnumArray(rules.Backend, ?anyerror).init(.{ + .metal27 = null, + .hip = null, + .metal2b = error.UnsupportedQwenConfig, + .cuda = error.UnsupportedActivation, + }); + for (std.enums.values(rules.Backend)) |b| { + const was = old.run(b, r.tower); + const now = entry(b, r.json); + errdefer std.debug.print("{s}: old {any}, now {any}\n", .{ @tagName(b), was, now }); + try t.expectEqual(std.meta.isError(was), std.meta.isError(now)); + if (want.get(b)) |e| try t.expectError(e, now) else try now; + } } test "qwen35 rules: every row and value through every entry point admits as main did, refused by the row's word" { From 96fb5479636aebd45719003b5987310fc4a0613e Mon Sep 17 00:00:00 2001 From: Shinto C V <11365900+cshintov@users.noreply.github.com> Date: Fri, 20 Nov 2026 12:07:55 +0530 Subject: [PATCH 10/13] qwen35 rules: the zero head count test counts the 35B-A3B's Metal 27B and HIP bases --- zig/qwen35_rules_host.zig | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/zig/qwen35_rules_host.zig b/zig/qwen35_rules_host.zig index b001091c24c..b52c8d74bde 100644 --- a/zig/qwen35_rules_host.zig +++ b/zig/qwen35_rules_host.zig @@ -222,7 +222,7 @@ test "qwen35 rules: a head count of 0 is refused by name at every entry point, b } }; errdefer std.debug.print("cases {any}, without head_dim {d}\n", .{ cases.values, derived }); - // four zeros on each admitted base: CUDA 7, Metal 27B 8, Metal 2B 1, HIP 18 (13 of all without head_dim) - try t.expectEqual([_]usize{ 4 * 7, 4 * 8, 4 * 1, 4 * 18 }, cases.values); - try t.expectEqual(@as(usize, 13), derived); + // four zeros on each admitted base: CUDA 7, Metal 27B 10, Metal 2B 1, HIP 20 (15 of all without head_dim) + try t.expectEqual([_]usize{ 4 * 7, 4 * 10, 4 * 1, 4 * 20 }, cases.values); + try t.expectEqual(@as(usize, 15), derived); } From f76394203559838818d61919d293c9a12a7fbda9 Mon Sep 17 00:00:00 2001 From: Shinto C V <11365900+cshintov@users.noreply.github.com> Date: Sun, 22 Nov 2026 00:22:13 +0000 Subject: [PATCH 11/13] qwen27: the stage recorder is built into tf-qwen27-run only; --vision refuses the 35B-A3B --- zig/src/families/qwen27/decode_round.zig | 12 +++++------- zig/src/families/qwen27/forward.zig | 22 +++++++++++----------- zig/src/families/qwen27/model.zig | 11 ++++++++--- zig/src/families/qwen27/stage_planes.zig | 19 ++++++++++--------- zig/src/native/qwen27_images.zig | 4 ++++ zig/tests/qwen27/run.zig | 6 ++++-- 6 files changed, 42 insertions(+), 32 deletions(-) diff --git a/zig/src/families/qwen27/decode_round.zig b/zig/src/families/qwen27/decode_round.zig index 53ebe63692b..13264bd9e04 100644 --- a/zig/src/families/qwen27/decode_round.zig +++ b/zig/src/families/qwen27/decode_round.zig @@ -67,8 +67,6 @@ pub const Runner = struct { capture_taps: bool = false, /// The last tapped pass's rows by slot: their cache start, first frame row and count (0: none held). tapped: [attn.planning.max_streams]Tapped = @splat(.{}), - /// Staged references for one stream's rounds; null (the default) records nothing. - stages: ?*@import("stage_planes.zig").Planes = null, tail: ?forward.Tail = null, accepted_chain: bool = false, /// The running pass's prompt tail start (prompt_tail.zig): its last layer's q, o and MLP run from this row on. @@ -284,7 +282,7 @@ pub const Runner = struct { // A rank's head writes only this rank's vocabulary columns; the tail's matcher reads the whole vocabulary. if (r.tail != null and r.reduce != null) return error.TailOnRank; for (round.slots, round.windows) |slot, window| if (slot >= r.ready or r.offsets[slot] != window.start) return error.CachePositionDiffers; - if (r.stages != null) try stage_planes.admit(round.windows); // refused before the round touches any state + if (stage_planes.on) if (stage_planes.active != null) try stage_planes.admit(round.windows); // refused before the round touches any state for (round.slots, round.windows) |slot, window| try r.cover(slot, window.start + @as(u32, @intCast(window.parents.len))); for (round.slots, round.windows) |slot, window| try r.reserve(slot, window.start + @as(u32, @intCast(window.parents.len))); const paths = try r.allocator.alloc([]const u32, round.windows.len); @@ -326,18 +324,18 @@ pub const Runner = struct { r.taps.begin(); r.tapped = @splat(.{}); } - if (r.stages) |planes| planes.begin(); + if (stage_planes.on) if (stage_planes.active) |planes| planes.begin(); const pool = mtl.objc.Pool.push(); defer pool.pop(); const spanned = if (r.trace) |t| t.spanned else 0; // a profiled pass's spans commit buffers of their own const handed = if (r.model.ane) |share| share.gpu_seconds else 0; var tail_facts = @import("prompt_tail.zig").facts(r, head, accepted, placed.images != null or r.images != null); - tail_facts.last_tapped = tail_facts.last_tapped or r.stages != null; // staged references read the last layer's rows + if (stage_planes.on) tail_facts.last_tapped = tail_facts.last_tapped or stage_planes.active != null; // staged references read the last layer's rows r.tail_from = @import("prompt_tail.zig").first(tail_facts, round.ids.len, round.windows.len); defer r.tail_from = null; if (r.tail_from) |t0| r.model.frame.setTail(t0, @intCast(round.ids.len)); const keys = @import("prompt_tail.zig").keysOnly(tail_facts); - var stages = forward.Stages{ .model = r.model, .rows = @intCast(round.ids.len), .hooks = .{ .ptr = r, .gdn = gdnForward, .attention = attentionForward, .tap = if (r.capture_taps) tap else null, .keys = if (keys) prompt_tail.keysForward else null, .stage = if (r.stages) |p| .{ .planes = p, .glue = r.model.glue } else null }, .head = head, .tail = r.tail, .images = placed.images, .reduce = r.reduce, .picks = r.picks, .tail_from = r.tail_from }; + var stages = forward.Stages{ .model = r.model, .rows = @intCast(round.ids.len), .hooks = .{ .ptr = r, .gdn = gdnForward, .attention = attentionForward, .tap = if (r.capture_taps) tap else null, .keys = if (keys) prompt_tail.keysForward else null }, .head = head, .tail = r.tail, .images = placed.images, .reduce = r.reduce, .picks = r.picks, .tail_from = r.tail_from }; r.last_gpu_seconds = @import("core").segments.runCommitting(r.model.device, &.{r.model.queue}, r.model.config.layers, .concurrent, &stages, commit_every) catch |err| { r.failed = true; return err; @@ -362,7 +360,7 @@ pub const Runner = struct { if (accepted) { for (round.slots, round.windows) |slot, window| r.offsets[slot] = window.start + @as(u32, @intCast(window.parents.len)); } else r.active = fingerprint(round); - if (r.stages) |planes| try planes.end(round.windows[0].start); // after the round is committed, so a refusal leaves it whole + if (stage_planes.on) if (stage_planes.active) |planes| try planes.end(round.windows[0].start); // after the round is committed, so a refusal leaves it whole } /// One MTP head pass (mtp.zig `pass`); a round left to keep reads nothing it writes. diff --git a/zig/src/families/qwen27/forward.zig b/zig/src/families/qwen27/forward.zig index beb7b49372a..896ca2456e8 100644 --- a/zig/src/families/qwen27/forward.zig +++ b/zig/src/families/qwen27/forward.zig @@ -16,9 +16,9 @@ pub const Mixer = struct { tap: ?*const fn (*anyopaque, mtl.ComputeEncoder, usize, Ref, u32) anyerror!void = null, /// A pass that keeps no row and has no other reader of the last layer: that layer writes keys and values only. keys: ?*const fn (*anyopaque, mtl.ComputeEncoder, usize, wts.Attention, *Frame, u32) anyerror!void = null, - /// Staged references (off unless asked for): the stream after each stage, the final norm and the head's rows. - stage: ?@import("stage_planes.zig").Hook = null, }; +/// Staged references (tf-qwen27-run only): the stream after each stage, the final norm and the head's rows. +const stage_planes = @import("stage_planes.zig"); /// One exchange: `x` its index, `ref` this rank's `width` columns of the seam in the window's slot for x. pub const Seam = struct { x: u32, ref: Ref }; @@ -103,7 +103,7 @@ pub const Stages = struct { m.glue.imageRows(lane.enc, s.hidden, rows, m.frame.get(.takes), @intCast(m.config.hidden), s.rows); lane.enc.barrier(); } - if (s.hooks.stage) |stage| try stage.record(lane.enc, .embed, s.hidden, s.rows); + if (stage_planes.on) try stage_planes.record(s.model.glue, lane.enc, .embed, s.hidden, s.rows); } pub fn wait(_: *Stages, _: usize) @import("core").segments.Wait { return .mixer; @@ -120,7 +120,7 @@ pub const Stages = struct { if (s.pending != null) { std.mem.swap(Ref, &s.hidden, &s.residual); if (s.hooks.tap) |tap| try tap(s.hooks.ptr, e, index - 1, s.hidden, s.rows); - if (s.hooks.stage) |stage| try stage.record(e, .{ .block = index - 1 }, s.hidden, s.rows); + if (stage_planes.on) try stage_planes.record(s.model.glue, e, .{ .block = index - 1 }, s.hidden, s.rows); } } /// The last layer of a pass whose other rows nothing reads: q, attention, o and the MLP have no reader. @@ -177,7 +177,7 @@ pub const Stages = struct { try m.kernels.norm(e, t.at(s.hidden, h), t.at(f.get(.output), h), wts.ref(layer.post_norm), f.get(.eps), t.dims, t.at(s.residual, h), t.at(f.get(.input), h), t.sums(f.get(.sums)), h, t.n); e.barrier(); std.mem.swap(Ref, &s.hidden, &s.residual); - if (s.hooks.stage) |stage| try stage.record(e, .{ .mixer = index }, s.hidden, s.rows); + if (stage_planes.on) try stage_planes.record(s.model.glue, e, .{ .mixer = index }, s.hidden, s.rows); if (layer.moe) |*mo| if (!m.moe.?.sorted(mo, m.kernels.prompt)) { // decode rows: the routed block runs the shared expert as one more slot of the experts' kernel try m.moe.?.block(lane.enc, m.config, mo, f, s.rows, m.kernels.prompt); @@ -269,10 +269,10 @@ pub const Stages = struct { e.barrier(); std.mem.swap(Ref, &s.hidden, &s.residual); if (s.hooks.tap) |tap| try tap(s.hooks.ptr, e, m.config.layers - 1, s.hidden, s.rows); - if (s.hooks.stage) |stage| { + if (stage_planes.on) { // the last block is the residual stream; final is the normed rows the head reads (f.input) - try stage.record(e, .{ .block = m.config.layers - 1 }, s.hidden, s.rows); - try stage.record(e, .final, f.get(.input), s.rows); + try stage_planes.record(m.glue, e, .{ .block = m.config.layers - 1 }, s.hidden, s.rows); + try stage_planes.record(m.glue, e, .final, f.get(.input), s.rows); } if (s.head == .all and s.rows > @import("gpu_frame.zig").logit_rows) return error.BadFrameRows; if (s.head != .none) { @@ -283,10 +283,10 @@ pub const Stages = struct { head_sums.ref.offset += @as(usize, s.rows - 1) * 4; } try m.kernels.quant(e, m.weights.head, input, head_sums, f.get(.dims), s.logits orelse f.get(.logits), if (s.head == .last) 1 else s.rows); - if (s.hooks.stage) |stage| { + if (stage_planes.on) if (stage_planes.active != null) { e.barrier(); - try stage.record(e, .logits, f.get(.logits), if (s.head == .last) 1 else s.rows); - } + try stage_planes.record(m.glue, e, .logits, f.get(.logits), if (s.head == .last) 1 else s.rows); + }; } e.barrier(); if (s.reduce) |r| { diff --git a/zig/src/families/qwen27/model.zig b/zig/src/families/qwen27/model.zig index 8c056376a86..444c1f6018e 100644 --- a/zig/src/families/qwen27/model.zig +++ b/zig/src/families/qwen27/model.zig @@ -261,12 +261,15 @@ pub fn supported(c: cfg.Config) !void { const dense = qualifiedSize(c) and c.kv_heads == 4 and c.k_heads == 16 and !c.moe(); // Ornith-1.5-122B: 256 experts of 1,024 and a shared expert of 1,024 over 3,072, 32 heads over 2 of 256 const routed = c.hidden == 3072 and c.intermediate == 1024 and c.layers == 48 and c.heads == 32 and c.kv_heads == 2 and c.k_heads == 16 and c.v_heads == 64 and c.experts == 256 and c.top_k == 8 and c.moe_intermediate == 1024; - // Qwen3.6-35B-A3B: 256 experts of 512 and a shared expert of 512 over 2,048, 16 heads over 2 of 256 - const a3b = c.hidden == 2048 and c.intermediate == 512 and c.layers == 40 and c.heads == 16 and c.kv_heads == 2 and c.k_heads == 16 and c.v_heads == 32 and c.experts == 256 and c.top_k == 8 and c.moe_intermediate == 512; - if (!(dense or routed or a3b) or c.vocab != 248320) return error.UnqualifiedQwenShape; + if (!(dense or routed or a3b(c)) or c.vocab != 248320) return error.UnqualifiedQwenShape; try @import("geometry.zig").supported(c); } +/// Qwen3.6-35B-A3B: 256 experts of 512 and a shared expert of 512 over 2,048, 16 heads over 2 of 256 (text only). +pub fn a3b(c: cfg.Config) bool { + return c.hidden == 2048 and c.intermediate == 512 and c.layers == 40 and c.heads == 16 and c.kv_heads == 2 and c.k_heads == 16 and c.v_heads == 32 and c.experts == 256 and c.top_k == 8 and c.moe_intermediate == 512; +} + fn qualifiedGeneration(generation: u32) bool { return generation >= 13 and generation <= 18; } @@ -274,7 +277,9 @@ fn qualifiedGeneration(generation: u32) bool { test "the qualified shapes: the dense 27B, Ornith-1.5-122B and Qwen3.6-35B-A3B; a 35B of other widths is refused" { var c = try cfg.parse(std.testing.allocator, @import("config_test.zig").a3b_json, null); try supported(c); + try std.testing.expect(a3b(c)); // --vision refuses it by this c.moe_intermediate = 1024; + try std.testing.expect(!a3b(c)); try std.testing.expectError(error.UnqualifiedQwenShape, supported(c)); c.moe_intermediate = 512; c.top_k = 10; diff --git a/zig/src/families/qwen27/stage_planes.zig b/zig/src/families/qwen27/stage_planes.zig index c7bae7eb168..08f726fb799 100644 --- a/zig/src/families/qwen27/stage_planes.zig +++ b/zig/src/families/qwen27/stage_planes.zig @@ -4,6 +4,12 @@ const mtl = @import("metal"); const Ref = @import("projection.zig").Ref; const Glue = @import("glue_gpu.zig").Kernels; const stages = @import("core").qwen35_stages; +const root = @import("root"); + +/// Built in only when the program's root says `pub const qwen27_stages = true` (tf-qwen27-run): served code has none. +pub const on = @hasDecl(root, "qwen27_stages") and root.qwen27_stages; +/// The planes a tool's one runner records into (null: none); void unless built in, so no served type changes. +pub var active: if (on) ?*Planes else void = if (on) null else {}; pub const Planes = struct { buffer: mtl.Buffer, @@ -40,12 +46,7 @@ pub fn admit(windows: anytype) !void { try stages.admit(windows.len, windows.len == 1 and stages.isChain(windows[0].parents), true); } -/// The forward pass's stage hook: each stage's rows into `planes` through the model's glue. -pub const Hook = struct { - planes: *Planes, - glue: Glue, - - pub fn record(h: Hook, e: mtl.ComputeEncoder, at: stages.Point, x: Ref, rows: u32) !void { - try h.planes.record(h.glue, e, at, x, rows); - } -}; +/// A pass's stage rows into the active planes, when stages are built in and asked for. +pub inline fn record(glue: Glue, e: mtl.ComputeEncoder, at: stages.Point, x: Ref, rows: u32) !void { + if (on) if (active) |p| try p.record(glue, e, at, x, rows); +} diff --git a/zig/src/native/qwen27_images.zig b/zig/src/native/qwen27_images.zig index 443c0f46e0c..c42c04b20de 100644 --- a/zig/src/native/qwen27_images.zig +++ b/zig/src/native/qwen27_images.zig @@ -44,6 +44,10 @@ pub const Vision = struct { /// The checkpoint's tower for `model`'s width under its rope, for `o.image_tokens` image tokens a request. pub fn open(gpa: Allocator, io: std.Io, model: *const q.model.Model, dir: []const u8, o: api.VisionOpen, a: Allocator, why: *[]const u8) !*Vision { + if (q.model.a3b(model.config)) { + why.* = "--vision: Qwen3.6-35B-A3B is served as text only; its image path is not qualified"; + return error.VisionUnqualified; + } const read = struct { fn f(al: Allocator, i: std.Io, d: []const u8, name: []const u8) ?[]const u8 { const path = std.fs.path.join(al, &.{ d, name }) catch return null; diff --git a/zig/tests/qwen27/run.zig b/zig/tests/qwen27/run.zig index fe48aa651e3..a1be85fe5b6 100644 --- a/zig/tests/qwen27/run.zig +++ b/zig/tests/qwen27/run.zig @@ -1,5 +1,7 @@ //! The real-weight gate. Help returns before any device or checkpoint access. const std = @import("std"); +/// --stages: the qwen27 stage recorder is built into this tool only (stage_planes.on). +pub const qwen27_stages = true; const q = @import("qwen27"); const mtl = @import("metal"); const sources = @import("qwen_runtime_sources"); @@ -185,7 +187,7 @@ pub fn main(init: std.process.Init) !void { if (stages_dir != null) { recorder = try core.qwen35_stages.Recorder.init(init.gpa, m.config.layers, m.config.hidden, m.config.vocab); planes = try q.stage_planes.Planes.init(m.device, &recorder.?, m.frame.capacity, @min(m.frame.capacity, q.gpu_frame.logit_rows)); - runner.stages = &planes.?; + q.stage_planes.active = &planes.?; } const start = std.Io.Clock.awake.now(io); try s.prefill(ids, chunk); @@ -196,7 +198,7 @@ pub fn main(init: std.process.Init) !void { const generation = try generated(a, s, count, force, expected, if (profile_steps > 0) &trace else null, profile_steps, teacher); const out = generation.tokens; const decode_ns = decode_start.durationTo(std.Io.Clock.awake.now(io)).toNanoseconds(); - runner.stages = null; + q.stage_planes.active = null; if (stages_dir) |dir| try recorder.?.write(io, dir); const decoded = if (compare > 0) try s.fingerprint() else digest; const reference_equal = if (expected) |wanted| std.mem.eql(u32, out, wanted) else false; From 1b0a880bb49c18b4ed23c44ff2581be25c8a0869 Mon Sep 17 00:00:00 2001 From: Shinto C V <11365900+cshintov@users.noreply.github.com> Date: Sun, 22 Nov 2026 00:23:11 +0000 Subject: [PATCH 12/13] qwen27: stage_planes.begin starts a round's planes and marks the last layer read on main's prompt tail facts --- zig/src/families/qwen27/decode_round.zig | 4 +--- zig/src/families/qwen27/stage_planes.zig | 10 ++++++++++ 2 files changed, 11 insertions(+), 3 deletions(-) diff --git a/zig/src/families/qwen27/decode_round.zig b/zig/src/families/qwen27/decode_round.zig index 13264bd9e04..741bd733429 100644 --- a/zig/src/families/qwen27/decode_round.zig +++ b/zig/src/families/qwen27/decode_round.zig @@ -324,13 +324,11 @@ pub const Runner = struct { r.taps.begin(); r.tapped = @splat(.{}); } - if (stage_planes.on) if (stage_planes.active) |planes| planes.begin(); const pool = mtl.objc.Pool.push(); defer pool.pop(); const spanned = if (r.trace) |t| t.spanned else 0; // a profiled pass's spans commit buffers of their own const handed = if (r.model.ane) |share| share.gpu_seconds else 0; - var tail_facts = @import("prompt_tail.zig").facts(r, head, accepted, placed.images != null or r.images != null); - if (stage_planes.on) tail_facts.last_tapped = tail_facts.last_tapped or stage_planes.active != null; // staged references read the last layer's rows + const tail_facts = stage_planes.begin(@import("prompt_tail.zig").facts(r, head, accepted, placed.images != null or r.images != null)); r.tail_from = @import("prompt_tail.zig").first(tail_facts, round.ids.len, round.windows.len); defer r.tail_from = null; if (r.tail_from) |t0| r.model.frame.setTail(t0, @intCast(round.ids.len)); diff --git a/zig/src/families/qwen27/stage_planes.zig b/zig/src/families/qwen27/stage_planes.zig index 08f726fb799..fbbc7ed9d12 100644 --- a/zig/src/families/qwen27/stage_planes.zig +++ b/zig/src/families/qwen27/stage_planes.zig @@ -46,6 +46,16 @@ pub fn admit(windows: anytype) !void { try stages.admit(windows.len, windows.len == 1 and stages.isChain(windows[0].parents), true); } +/// A round's prompt tail facts with its planes begun: recording reads the last layer's stream and final norm. +pub inline fn begin(facts: anytype) @TypeOf(facts) { + var out = facts; + if (on) if (active) |p| { + p.begin(); + out.last_tapped = true; + }; + return out; +} + /// A pass's stage rows into the active planes, when stages are built in and asked for. pub inline fn record(glue: Glue, e: mtl.ComputeEncoder, at: stages.Point, x: Ref, rows: u32) !void { if (on) if (active) |p| try p.record(glue, e, at, x, rows); From c278a428aa1024139718d8a850d20fb12b236b53 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Tue, 24 Nov 2026 04:50:24 +0000 Subject: [PATCH 13/13] changelog: #3239 under Unreleased --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 092de38a6a9..e142af196bc 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 +- Qwen3.6-35B-A3B on Metal: the text-only checkpoint serves on the routed expert path, `--vision` refuses it by name, and `tf-qwen27-run --stages DIR` writes each layer's stream for a float64 comparison (#3239). Thanks to @cshintov. + - Metal Qwen3.8-27B with MTP drafts: `TF_Q27_MTP_GPU_PICK=1` runs each MTP absorb in one command buffer and picks draft tokens on the GPU, removing two blocking waits per absorb and the CPU pass over the vocabulary; off by default (#N). - Idol: octree and decode-trace allocation failures now unwind cleanly and free what they hold, with successful output unchanged (#4304).