From 5858b564bbff3c5d621a5c0a1fb8bb1a6c80dff1 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Mon, 23 Nov 2026 20:31:46 +0000 Subject: [PATCH 01/11] xpu: route Qwen27 and TP peer opens through detectDeviceId Issue #4778: the hard-coded B70 ID refused Arc Pro B60 before any kernel ran. Share Flash Next detection with Qwen27 and tp_bench; XPU_DEVICE_ID still overrides discovery. The fake-opener host contract covers 0xe211 and 0xe223 without a device. --- zig/build/xpu.zig | 5 ++ zig/src/families/flashnext/xpu_store.zig | 29 +-------- zig/src/xpu/device_id.zig | 78 ++++++++++++++++++++++++ zig/src/xpu/qwen27.zig | 3 +- zig/src/xpu/tp_bench.zig | 5 +- 5 files changed, 89 insertions(+), 31 deletions(-) create mode 100644 zig/src/xpu/device_id.zig diff --git a/zig/build/xpu.zig b/zig/build/xpu.zig index 5bd83466f4f..ed5cb06b37a 100644 --- a/zig/build/xpu.zig +++ b/zig/build/xpu.zig @@ -425,6 +425,11 @@ pub fn hostTests(b: *std.Build, step: *std.Build.Step) void { const shape_tests = b.addRunArtifact(b.addTest(.{ .root_module = shape })); b.step("test-qwen27-config-xpu-host", "The XPU 27B runner's config.json shape and layer pattern without devices or ocloc").dependOn(&shape_tests.step); step.dependOn(&shape_tests.step); + // Shared selection for Qwen27 and the TP benchmark: its fake opener needs no device + const device = b.createModule(.{ .root_source_file = b.path("zig/src/xpu/device_id.zig"), .target = host, .optimize = .debug, .link_libc = true, .imports = &.{.{ .name = "ze", .module = ze }} }); + const device_tests = b.addRunArtifact(b.addTest(.{ .root_module = device })); + b.step("test-xpu-device-id-host", "XPU peer opens honor detected B60 and B70 IDs and the explicit override").dependOn(&device_tests.step); + step.dependOn(&device_tests.step); const tail_tests = b.addRunArtifact(b.addTest(.{ .root_module = qwen, .filters = &.{"xpu prompt tail:"} })); b.step("test-qwen27-prompt-tail-xpu-host", "The XPU 27B layer-63 prompt-tail plan without devices").dependOn(&tail_tests.step); step.dependOn(&tail_tests.step); diff --git a/zig/src/families/flashnext/xpu_store.zig b/zig/src/families/flashnext/xpu_store.zig index ff3e380202d..647927b9262 100644 --- a/zig/src/families/flashnext/xpu_store.zig +++ b/zig/src/families/flashnext/xpu_store.zig @@ -321,34 +321,7 @@ pub fn off(p: *anyopaque, bytes: usize) *anyopaque { return @ptrFromInt(@intFromPtr(p) + bytes); } -/// Discover the first Xe2 GPU's PCI device ID on the system (defaulting to 0xe211 B70 if XPU_DEVICE_ID is unset). -pub fn detectDeviceId() !u32 { - if (try @import("sys").environment.read(?u32, "XPU_DEVICE_ID", null)) |id| return id; - var lib = std.DynLib.open("libze_loader.so.1") catch return error.LoaderUnavailable; - defer lib.close(); - const api = try ze.resolve(ze.Api, &lib); - try ze.check(api.zeInit(1)); - var nd: u32 = 0; - try ze.check(api.zeDriverGet(&nd, null)); - var drivers: [8]ze.H = @splat(null); - nd = @min(nd, drivers.len); - try ze.check(api.zeDriverGet(&nd, &drivers)); - for (drivers[0..nd]) |drv| { - if (drv == null) continue; - var nv: u32 = 0; - try ze.check(api.zeDeviceGet(drv, &nv, null)); - var devs: [16]ze.H = @splat(null); - nv = @min(nv, devs.len); - try ze.check(api.zeDeviceGet(drv, &nv, &devs)); - for (devs[0..nv]) |dev| { - if (dev == null) continue; - var p: ze.DeviceProperties = .{}; - try ze.check(api.zeDeviceGetProperties(dev, &p)); - if (p.deviceId != 0) return p.deviceId; - } - } - return error.NoDevice; -} +pub const detectDeviceId = @import("../../xpu/device_id.zig").detectDeviceId; // Safetensors Store (drops non-PLE shard pages during load to preserve host RAM) diff --git a/zig/src/xpu/device_id.zig b/zig/src/xpu/device_id.zig new file mode 100644 index 00000000000..ccf6bd4decb --- /dev/null +++ b/zig/src/xpu/device_id.zig @@ -0,0 +1,78 @@ +//! Shared Level Zero device selection and peer opening for the Xe2 runners. +const std = @import("std"); +const ze = @import("ze"); + +/// Discover the first Level Zero device's PCI ID; XPU_DEVICE_ID bypasses discovery (for example 0xe211 B60). +pub fn detectDeviceId() !u32 { + if (try @import("sys").environment.read(?u32, "XPU_DEVICE_ID", null)) |id| return id; + var lib = std.DynLib.open("libze_loader.so.1") catch return error.LoaderUnavailable; + defer lib.close(); + const api = try ze.resolve(ze.Api, &lib); + try ze.check(api.zeInit(1)); + var nd: u32 = 0; + try ze.check(api.zeDriverGet(&nd, null)); + var drivers: [8]ze.H = @splat(null); + nd = @min(nd, drivers.len); + try ze.check(api.zeDriverGet(&nd, &drivers)); + for (drivers[0..nd]) |drv| { + if (drv == null) continue; + var nv: u32 = 0; + try ze.check(api.zeDeviceGet(drv, &nv, null)); + var devs: [16]ze.H = @splat(null); + nv = @min(nv, devs.len); + try ze.check(api.zeDeviceGet(drv, &nv, &devs)); + for (devs[0..nv]) |dev| { + if (dev == null) continue; + var p: ze.DeviceProperties = .{}; + try ze.check(api.zeDeviceGetProperties(dev, &p)); + if (p.deviceId != 0) return p.deviceId; + } + } + return error.NoDevice; +} + +pub fn openPeers(out: []ze.Gpu) !void { + return openPeersWith(out, detectDeviceId, ze.Gpu.openPeers); +} + +fn openPeersWith(out: []ze.Gpu, detect: anytype, open: anytype) !void { + const id = try detect(); + try open(id, out); +} + +test "XPU device selection: B60 and B70 IDs reach the peer opener" { + const Fake = struct { + var selected: u32 = 0; + var opened: u32 = 0; + fn detect() !u32 { + return selected; + } + fn open(id: u32, out: []ze.Gpu) !void { + opened = id; + try std.testing.expectEqual(@as(usize, 2), out.len); + } + }; + var out: [2]ze.Gpu = undefined; + for ([_]u32{ 0xe211, 0xe223 }) |id| { + Fake.selected = id; + Fake.opened = 0; + try openPeersWith(&out, Fake.detect, Fake.open); + try std.testing.expectEqual(id, Fake.opened); + } +} + +test "XPU device selection: the environment override needs no device or driver" { + const sys = @import("sys"); + const name = "XPU_DEVICE_ID"; + const before = if (sys.getenv(name)) |raw| try std.testing.allocator.dupeSentinel(u8, raw, 0) else null; + defer { + if (before) |raw| { + _ = sys.env.setenv(name, raw, 1); + std.testing.allocator.free(raw); + } else _ = sys.env.unsetenv(name); + } + for ([_][:0]const u8{ "0xe211", "0xe223" }, [_]u32{ 0xe211, 0xe223 }) |raw, id| { + try std.testing.expectEqual(@as(c_int, 0), sys.env.setenv(name, raw, 1)); + try std.testing.expectEqual(id, try detectDeviceId()); + } +} diff --git a/zig/src/xpu/qwen27.zig b/zig/src/xpu/qwen27.zig index 86843285dd0..7e632629e38 100644 --- a/zig/src/xpu/qwen27.zig +++ b/zig/src/xpu/qwen27.zig @@ -3,6 +3,7 @@ const std = @import("std"); pub const ze = @import("ze"); const kb = @import("xpu_qwen27_kernels"); const dev = @import("dev.zig"); +const device_id = @import("device_id.zig"); const fwd = @import("forward.zig"); const loader = @import("load.zig"); const multi = @import("runner_multi.zig"); @@ -435,7 +436,7 @@ pub const Runner = struct { } var open_gpus: [4]ze.Gpu = undefined; - try ze.Gpu.openPeers(0xe223, open_gpus[0..tp_deg]); + try device_id.openPeers(open_gpus[0..tp_deg]); errdefer ze.Gpu.closePeers(open_gpus[0..tp_deg]); const r = try alloc.create(Runner); diff --git a/zig/src/xpu/tp_bench.zig b/zig/src/xpu/tp_bench.zig index 2b92d04153d..163767dcb4e 100644 --- a/zig/src/xpu/tp_bench.zig +++ b/zig/src/xpu/tp_bench.zig @@ -1,6 +1,7 @@ -//! Phase 1 benchmark & bit-exactness verification for Level Zero P2P TP=2 and TP=4 collectives on Arc Pro B70. +//! Phase 1 benchmark & bit-exactness verification for Level Zero P2P TP=2 and TP=4 collectives on Arc Pro Xe2. const std = @import("std"); const ze = @import("ze"); +const device_id = @import("device_id.zig"); const tp_mod = @import("tp.zig"); const kb = @import("xpu_tp_kernels"); @@ -18,7 +19,7 @@ fn f32ToF16Rte(v: f32) u16 { fn runSuite(tp_deg: usize) !void { const alloc = std.heap.c_allocator; var gpus: [4]ze.Gpu = undefined; - ze.Gpu.openPeers(0xe223, gpus[0..tp_deg]) catch |err| { + device_id.openPeers(gpus[0..tp_deg]) catch |err| { std.debug.print("skipped TP={d}: {s}\n", .{ tp_deg, @errorName(err) }); return; }; From 8b93bbdb5c91219cd9bca53bdd4e72f26fd2cf86 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Mon, 23 Nov 2026 20:48:56 +0000 Subject: [PATCH 02/11] xpu: keep B70 default until NoDevice --- zig/src/xpu/device_id.zig | 109 +++++++++++++++++++++++++++++++++----- 1 file changed, 95 insertions(+), 14 deletions(-) diff --git a/zig/src/xpu/device_id.zig b/zig/src/xpu/device_id.zig index ccf6bd4decb..e65502f8405 100644 --- a/zig/src/xpu/device_id.zig +++ b/zig/src/xpu/device_id.zig @@ -32,43 +32,124 @@ pub fn detectDeviceId() !u32 { } pub fn openPeers(out: []ze.Gpu) !void { + if (try @import("sys").environment.read(?u32, "XPU_DEVICE_ID", null)) |id| return ze.Gpu.openPeers(id, out); return openPeersWith(out, detectDeviceId, ze.Gpu.openPeers); } +// Qwen27/TP preserve their incumbent B70 default; only NoDevice permits discovery. fn openPeersWith(out: []ze.Gpu, detect: anytype, open: anytype) !void { - const id = try detect(); - try open(id, out); + open(0xe223, out) catch |err| { + if (err != error.NoDevice) return err; + const id = try detect(); + if (id == 0xe223) return error.NoDevice; + return open(id, out); + }; } -test "XPU device selection: B60 and B70 IDs reach the peer opener" { +test "XPU device selection: B60 discovery follows only a missing B70 group" { const Fake = struct { - var selected: u32 = 0; - var opened: u32 = 0; + var allow_b60: bool = true; + var detected: u32 = 0; + var detect_calls: usize = 0; + var attempts: [2]u32 = .{ 0, 0 }; + var opened: usize = 0; fn detect() !u32 { - return selected; + detect_calls += 1; + return detected; } fn open(id: u32, out: []ze.Gpu) !void { - opened = id; try std.testing.expectEqual(@as(usize, 2), out.len); + attempts[opened] = id; + opened += 1; + if (id == 0xe223 or !allow_b60) return error.NoDevice; } }; var out: [2]ze.Gpu = undefined; - for ([_]u32{ 0xe211, 0xe223 }) |id| { - Fake.selected = id; + const Case = struct { allow_b60: bool, detected: u32 }; + for ([_]Case{ + .{ .allow_b60 = true, .detected = 0xe211 }, + .{ .allow_b60 = false, .detected = 0xe211 }, + .{ .allow_b60 = false, .detected = 0xe223 }, + }) |case| { + Fake.allow_b60 = case.allow_b60; + Fake.detected = case.detected; + Fake.detect_calls = 0; + Fake.attempts = .{ 0, 0 }; Fake.opened = 0; - try openPeersWith(&out, Fake.detect, Fake.open); - try std.testing.expectEqual(id, Fake.opened); + if (case.allow_b60) { + try openPeersWith(&out, Fake.detect, Fake.open); + } else { + try std.testing.expectError(error.NoDevice, openPeersWith(&out, Fake.detect, Fake.open)); + } + try std.testing.expectEqual(if (case.detected == 0xe211) @as(usize, 2) else 1, Fake.opened); + try std.testing.expectEqual(@as(u32, 0xe223), Fake.attempts[0]); + if (case.detected == 0xe211) try std.testing.expectEqual(@as(u32, 0xe211), Fake.attempts[1]); + try std.testing.expectEqual(@as(usize, 1), Fake.detect_calls); + } +} + +test "XPU device selection: opener errors other than NoDevice propagate" { + const Fake = struct { + var detect_calls: usize = 0; + var open_calls: usize = 0; + fn detect() !u32 { + detect_calls += 1; + return 0xe211; + } + fn open(id: u32, out: []ze.Gpu) !void { + try std.testing.expectEqual(@as(u32, 0xe223), id); + try std.testing.expectEqual(@as(usize, 1), out.len); + open_calls += 1; + return error.ZeFailed; + } + }; + var out: [1]ze.Gpu = undefined; + try std.testing.expectError(error.ZeFailed, openPeersWith(&out, Fake.detect, Fake.open)); + try std.testing.expectEqual(@as(usize, 1), Fake.open_calls); + try std.testing.expectEqual(@as(usize, 0), Fake.detect_calls); +} + +test "XPU device selection: mixed enumerations keep B70 for TP=1 and TP=2" { + const Fake = struct { + var detected: u32 = 0; + var detect_calls: usize = 0; + var opened: u32 = 0; + var peers: usize = 0; + fn detect() !u32 { + detect_calls += 1; + return detected; + } + fn open(id: u32, out: []ze.Gpu) !void { + opened = id; + peers = out.len; + } + }; + var out: [2]ze.Gpu = undefined; + for ([_]u32{ 0xe211, 0xe223 }) |first_detected| { + for ([_]usize{ 1, 2 }) |tp| { + Fake.detected = first_detected; + Fake.detect_calls = 0; + Fake.opened = 0; + Fake.peers = 0; + try openPeersWith(out[0..tp], Fake.detect, Fake.open); + try std.testing.expectEqual(@as(u32, 0xe223), Fake.opened); + try std.testing.expectEqual(tp, Fake.peers); + try std.testing.expectEqual(@as(usize, 0), Fake.detect_calls); + } } } test "XPU device selection: the environment override needs no device or driver" { const sys = @import("sys"); const name = "XPU_DEVICE_ID"; - const before = if (sys.getenv(name)) |raw| try std.testing.allocator.dupeSentinel(u8, raw, 0) else null; + const before = try sys.environment.read(?u32, name, null); defer { - if (before) |raw| { + if (before) |id| { + var storage: [16]u8 = undefined; + const text = std.fmt.bufPrint(&storage, "0x{x}", .{id}) catch unreachable; + storage[text.len] = 0; + const raw: [:0]const u8 = storage[0..text.len :0]; _ = sys.env.setenv(name, raw, 1); - std.testing.allocator.free(raw); } else _ = sys.env.unsetenv(name); } for ([_][:0]const u8{ "0xe211", "0xe223" }, [_]u32{ 0xe211, 0xe223 }) |raw, id| { From 1a3c32f14f1c40ac4ac48cf338570f96b6a30de8 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Mon, 23 Nov 2026 23:24:44 +0000 Subject: [PATCH 03/11] xpu: share device detection module --- zig/build/xpu.zig | 4 ++++ zig/src/families/flashnext/xpu_store.zig | 2 +- zig/src/xpu/qwen27.zig | 2 +- zig/src/xpu/tp_bench.zig | 2 +- 4 files changed, 7 insertions(+), 3 deletions(-) diff --git a/zig/build/xpu.zig b/zig/build/xpu.zig index ed5cb06b37a..5e94c9f9932 100644 --- a/zig/build/xpu.zig +++ b/zig/build/xpu.zig @@ -112,6 +112,7 @@ pub fn steps(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.buil ) }); const ze_mod = zeModule(b, target, optimize); const tp_mod = b.createModule(.{ .root_source_file = b.path("zig/src/xpu/tp.zig"), .target = target, .optimize = optimize, .link_libc = true }); + const device_id_mod = b.createModule(.{ .root_source_file = b.path("zig/src/xpu/device_id.zig"), .target = target, .optimize = optimize, .link_libc = true, .imports = &.{.{ .name = "ze", .module = ze_mod }} }); tp_mod.addImport("ze", ze_mod); // one `core` for these trees: the Gemma 4 config, the safetensors readers, Nemotron, the CLI and server const core = b.createModule(.{ .root_source_file = b.path("zig/src/core/root.zig"), .target = target, .optimize = .ReleaseSafe, .link_libc = true }); @@ -124,6 +125,7 @@ pub fn steps(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.buil const tpb = b.createModule(.{ .root_source_file = b.path("zig/src/xpu/tp_bench.zig"), .target = target, .optimize = optimize, .link_libc = true }); tpb.addImport("xpu_tp_kernels", embedded_tp); tpb.addImport("ze", ze_mod); + tpb.addImport("device_id", device_id_mod); const tpb_exe = b.addExecutable(.{ .name = "tf-xpu-tp-bench", .root_module = tpb }); b.step("xpu-tp-bench", "Build the multi-GPU Level Zero P2P TP=2/4 collective benchmark").dependOn(&b.addInstallArtifact(tpb_exe, .{}).step); } @@ -175,6 +177,7 @@ pub fn steps(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.buil const qwen27 = b.createModule(.{ .root_source_file = b.path("zig/src/xpu/qwen27.zig"), .target = target, .optimize = optimize, .link_libc = true }); qwen27.addImport("xpu_qwen27_kernels", embedded); qwen27.addImport("ze", ze_mod); + qwen27.addImport("device_id", device_id_mod); qwen27.addImport("xpu_tp", tp_mod); qwen27.addImport("core", core); // the runner's open rules (one runner at a time, every option back to the process's own), run on this host @@ -196,6 +199,7 @@ pub fn steps(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.buil flashnext.addImport("xpu_tp", tp_mod); flashnext.addImport("core", core); flashnext.addImport("ze", ze_mod); + flashnext.addImport("device_id", device_id_mod); engines.addImport("flashnext_xpu", flashnext); const gemma4 = b.createModule(.{ .root_source_file = b.path("zig/src/families/gemma4/xpu_engine.zig"), .target = target, .optimize = optimize, .link_libc = true }); gemma4.addImport("xpu_gemma4_kernels", embedded_g4); diff --git a/zig/src/families/flashnext/xpu_store.zig b/zig/src/families/flashnext/xpu_store.zig index 647927b9262..606c93fcfe7 100644 --- a/zig/src/families/flashnext/xpu_store.zig +++ b/zig/src/families/flashnext/xpu_store.zig @@ -321,7 +321,7 @@ pub fn off(p: *anyopaque, bytes: usize) *anyopaque { return @ptrFromInt(@intFromPtr(p) + bytes); } -pub const detectDeviceId = @import("../../xpu/device_id.zig").detectDeviceId; +pub const detectDeviceId = @import("device_id").detectDeviceId; // Safetensors Store (drops non-PLE shard pages during load to preserve host RAM) diff --git a/zig/src/xpu/qwen27.zig b/zig/src/xpu/qwen27.zig index 7e632629e38..cda1e712254 100644 --- a/zig/src/xpu/qwen27.zig +++ b/zig/src/xpu/qwen27.zig @@ -3,7 +3,7 @@ const std = @import("std"); pub const ze = @import("ze"); const kb = @import("xpu_qwen27_kernels"); const dev = @import("dev.zig"); -const device_id = @import("device_id.zig"); +const device_id = @import("device_id"); const fwd = @import("forward.zig"); const loader = @import("load.zig"); const multi = @import("runner_multi.zig"); diff --git a/zig/src/xpu/tp_bench.zig b/zig/src/xpu/tp_bench.zig index 163767dcb4e..b60f3491401 100644 --- a/zig/src/xpu/tp_bench.zig +++ b/zig/src/xpu/tp_bench.zig @@ -1,7 +1,7 @@ //! Phase 1 benchmark & bit-exactness verification for Level Zero P2P TP=2 and TP=4 collectives on Arc Pro Xe2. const std = @import("std"); const ze = @import("ze"); -const device_id = @import("device_id.zig"); +const device_id = @import("device_id"); const tp_mod = @import("tp.zig"); const kb = @import("xpu_tp_kernels"); From 8cbab16a88ee645e525db69f42fd47bd7f943f84 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Tue, 24 Nov 2026 13:20:58 +0000 Subject: [PATCH 04/11] xpu build: one host device_id module for the Qwen27, Flash Next and device-id tests qwen27.zig and flashnext/xpu_store.zig now import device_id, but hostTests() gave it only to the device-id test, so test-draft-xpu-host and test-slide-xpu-host could not compile (no module named 'device_id' within 'xpu_qwen27' / 'flashnext_xpu'). The host device_id module (on ze) is built once, before both host modules, and all three use it. --- zig/build/xpu.zig | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/zig/build/xpu.zig b/zig/build/xpu.zig index 5e94c9f9932..75a5545fd54 100644 --- a/zig/build/xpu.zig +++ b/zig/build/xpu.zig @@ -369,8 +369,10 @@ pub fn hostTests(b: *std.Build, step: *std.Build.Step) void { const tp_host = b.createModule(.{ .root_source_file = b.path("zig/src/xpu/tp.zig"), .target = host, .optimize = .debug, .link_libc = true }); tp_host.addImport("ze", ze); const empty = b.createModule(.{ .root_source_file = b.addWriteFiles().add("draft_xpu_images.zig", "pub const drafter = [_]u8{};\npub const glue_g = [_]u8{};\npub const glue = [_]u8{};\npub const glue_tp2 = [_]u8{};\npub const glue_tp4 = [_]u8{};\npub const rows = [_]u8{};\npub const rows_g = [_]u8{};\npub const decode = [_]u8{};\npub const decode_tp2 = [_]u8{};\npub const decode_tp4 = [_]u8{};\npub const gemm = [_]u8{};\npub const gdn = [_]u8{};\npub const tp = [_]u8{};\npub const flashnext = [_]u8{};\npub const ngen_wide = [_]u8{};\npub const ngen_narrow = [_]u8{};\npub const gemm128 = [_]u8{};\npub const ngen_wide128 = [_]u8{};\npub const ngen_narrow128 = [_]u8{};\npub const ngen_swiglu = [_]u8{};\npub const ngen_swiglu128 = [_]u8{};\npub const ngen_a8 = [_]u8{};\npub const ngen_a8_swiglu = [_]u8{};\npub const ngen_a4 = [_]u8{};\npub const ngen_geglu = [_]u8{};\n") }); - const qwen = b.createModule(.{ .root_source_file = b.path("zig/src/xpu/qwen27.zig"), .target = host, .optimize = .debug, .link_libc = true, .imports = &.{ .{ .name = "ze", .module = ze }, .{ .name = "xpu_tp", .module = tp_host }, .{ .name = "core", .module = core }, .{ .name = "xpu_qwen27_kernels", .module = empty } } }); - const fn_host = b.createModule(.{ .root_source_file = b.path("zig/src/families/flashnext/xpu_engine.zig"), .target = host, .optimize = .debug, .link_libc = true, .imports = &.{ .{ .name = "ze", .module = ze }, .{ .name = "core", .module = core }, .{ .name = "xpu_tp", .module = tp_host }, .{ .name = "xpu_flashnext_kernels", .module = empty } } }); + // Shared selection for Qwen27, Flash Next and the TP benchmark: its fake opener needs no device + const device = b.createModule(.{ .root_source_file = b.path("zig/src/xpu/device_id.zig"), .target = host, .optimize = .debug, .link_libc = true, .imports = &.{.{ .name = "ze", .module = ze }} }); + const qwen = b.createModule(.{ .root_source_file = b.path("zig/src/xpu/qwen27.zig"), .target = host, .optimize = .debug, .link_libc = true, .imports = &.{ .{ .name = "ze", .module = ze }, .{ .name = "xpu_tp", .module = tp_host }, .{ .name = "core", .module = core }, .{ .name = "xpu_qwen27_kernels", .module = empty }, .{ .name = "device_id", .module = device } } }); + const fn_host = b.createModule(.{ .root_source_file = b.path("zig/src/families/flashnext/xpu_engine.zig"), .target = host, .optimize = .debug, .link_libc = true, .imports = &.{ .{ .name = "ze", .module = ze }, .{ .name = "core", .module = core }, .{ .name = "xpu_tp", .module = tp_host }, .{ .name = "xpu_flashnext_kernels", .module = empty }, .{ .name = "device_id", .module = device } } }); const api = b.createModule(.{ .root_source_file = b.path("zig/src/core/engine_api.zig"), .target = host, .optimize = .debug, .link_libc = true, .imports = &.{.{ .name = "lanes", .module = lanes }} }); const sources = b.createModule(.{ .root_source_file = b.path("zig/src/native/draft_sources_xpu_test.zig"), .target = host, .optimize = .debug, .link_libc = true, .imports = &.{ .{ .name = "lanes", .module = lanes }, .{ .name = "engine_api", .module = api }, .{ .name = "xpu", .module = xpu }, .{ .name = "xpu_qwen27", .module = qwen }, .{ .name = "flashnext_xpu", .module = fn_host }, .{ .name = "nemotron_xpu", .module = mods.nemotron } } }); const gemma_native = b.createModule(.{ .root_source_file = b.path("zig/src/families/gemma4/xpu_engine.zig"), .target = host, .link_libc = true }); @@ -429,8 +431,6 @@ pub fn hostTests(b: *std.Build, step: *std.Build.Step) void { const shape_tests = b.addRunArtifact(b.addTest(.{ .root_module = shape })); b.step("test-qwen27-config-xpu-host", "The XPU 27B runner's config.json shape and layer pattern without devices or ocloc").dependOn(&shape_tests.step); step.dependOn(&shape_tests.step); - // Shared selection for Qwen27 and the TP benchmark: its fake opener needs no device - const device = b.createModule(.{ .root_source_file = b.path("zig/src/xpu/device_id.zig"), .target = host, .optimize = .debug, .link_libc = true, .imports = &.{.{ .name = "ze", .module = ze }} }); const device_tests = b.addRunArtifact(b.addTest(.{ .root_module = device })); b.step("test-xpu-device-id-host", "XPU peer opens honor detected B60 and B70 IDs and the explicit override").dependOn(&device_tests.step); step.dependOn(&device_tests.step); From a2e0a695a4cc74b618d3ec14009d4d27a975d237 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Tue, 24 Nov 2026 13:22:58 +0000 Subject: [PATCH 05/11] xpu: device detection reports no loader off Linux instead of opening one detectDeviceId opens Level Zero's libze_loader.so.1 with std.DynLib, which std does not provide for Windows, so test-xpu-device-id-host could not compile there ("unsupported platform"). After the XPU_DEVICE_ID override, a non-Linux build now returns error.LoaderUnavailable, the error a Linux host without the loader already gets. The check is comptime: Linux compiles exactly as before. --- zig/src/xpu/device_id.zig | 3 +++ 1 file changed, 3 insertions(+) diff --git a/zig/src/xpu/device_id.zig b/zig/src/xpu/device_id.zig index e65502f8405..2945ba93a68 100644 --- a/zig/src/xpu/device_id.zig +++ b/zig/src/xpu/device_id.zig @@ -1,10 +1,13 @@ //! Shared Level Zero device selection and peer opening for the Xe2 runners. const std = @import("std"); +const builtin = @import("builtin"); const ze = @import("ze"); /// Discover the first Level Zero device's PCI ID; XPU_DEVICE_ID bypasses discovery (for example 0xe211 B60). pub fn detectDeviceId() !u32 { if (try @import("sys").environment.read(?u32, "XPU_DEVICE_ID", null)) |id| return id; + // Level Zero's loader is Linux's libze_loader.so.1; elsewhere std.DynLib cannot open it, so no device is found + if (comptime builtin.os.tag != .linux) return error.LoaderUnavailable; var lib = std.DynLib.open("libze_loader.so.1") catch return error.LoaderUnavailable; defer lib.close(); const api = try ze.resolve(ze.Api, &lib); From 89cba54b7307d2bd2818d3c9355761d0ab7680db Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Tue, 24 Nov 2026 13:24:19 +0000 Subject: [PATCH 06/11] xpu build: device_id for the 27B device checks that compile qwen27.zig tail_test.zig, means_test.zig, seam_test.zig and close_test.zig import qwen27.zig, which now imports device_id, so compile-xpu-qwen27-tail-host, compile-xpu-qwen27-tail-linux and xpu-qwen27-tests failed the same way (no module named 'device_id' within 'root'). The host check takes the host device_id module, the Linux cross-compile its own on ze_linux, and the device tests the engine's device_id_mod. --- zig/build/xpu.zig | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/zig/build/xpu.zig b/zig/build/xpu.zig index 75a5545fd54..01c4fcfb9cc 100644 --- a/zig/build/xpu.zig +++ b/zig/build/xpu.zig @@ -169,6 +169,7 @@ pub fn steps(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.buil m.addImport("xpu_qwen27_kernels", embedded); m.addImport("ze", ze_mod); m.addImport("xpu_tp", tp_mod); + m.addImport("device_id", device_id_mod); m.addImport("core", runner_core); tests_step.dependOn(&b.addInstallArtifact(b.addExecutable(.{ .name = t[0], .root_module = m }), .{}).step); } @@ -441,7 +442,7 @@ pub fn hostTests(b: *std.Build, step: *std.Build.Step) void { b.step("test-flashnext-xpu-host", "The XPU Flash Next TP sharding, token-id bounds, and PLE hash checks without devices").dependOn(&fn_tests.step); step.dependOn(&fn_tests.step); // the device seam check is compiled on the host too; running it needs a B70 and a checkpoint - const tail_test = b.createModule(.{ .root_source_file = b.path("zig/src/xpu/tail_test.zig"), .target = host, .optimize = .debug, .link_libc = true, .imports = &.{ .{ .name = "ze", .module = ze }, .{ .name = "xpu_tp", .module = tp_host }, .{ .name = "core", .module = core }, .{ .name = "xpu_qwen27_kernels", .module = empty } } }); + const tail_test = b.createModule(.{ .root_source_file = b.path("zig/src/xpu/tail_test.zig"), .target = host, .optimize = .debug, .link_libc = true, .imports = &.{ .{ .name = "ze", .module = ze }, .{ .name = "xpu_tp", .module = tp_host }, .{ .name = "core", .module = core }, .{ .name = "xpu_qwen27_kernels", .module = empty }, .{ .name = "device_id", .module = device } } }); const tail_exe = b.addExecutable(.{ .name = "tf-xpu-qwen27-tail-test-host", .root_module = tail_test }); b.step("compile-xpu-qwen27-tail-host", "Compile the XPU 27B prompt-tail device check without devices").dependOn(&tail_exe.step); const linux = b.resolveTargetQuery(.{ .cpu_arch = .aarch64, .os_tag = .linux, .abi = .gnu }); @@ -451,6 +452,7 @@ pub fn hostTests(b: *std.Build, step: *std.Build.Step) void { const tp_linux = b.createModule(.{ .root_source_file = b.path("zig/src/xpu/tp.zig"), .target = linux, .optimize = .ReleaseFast, .link_libc = true }); tp_linux.addImport("ze", ze_linux); const empty_linux = b.createModule(.{ .root_source_file = b.addWriteFiles().add("draft_xpu_images.zig", "pub const drafter = [_]u8{};\npub const glue_g = [_]u8{};\npub const glue = [_]u8{};\npub const glue_tp2 = [_]u8{};\npub const glue_tp4 = [_]u8{};\npub const rows = [_]u8{};\npub const rows_g = [_]u8{};\npub const decode = [_]u8{};\npub const decode_tp2 = [_]u8{};\npub const decode_tp4 = [_]u8{};\npub const gemm = [_]u8{};\npub const gdn = [_]u8{};\npub const tp = [_]u8{};\npub const flashnext = [_]u8{};\npub const ngen_wide = [_]u8{};\npub const ngen_narrow = [_]u8{};\npub const gemm128 = [_]u8{};\npub const ngen_wide128 = [_]u8{};\npub const ngen_narrow128 = [_]u8{};\npub const ngen_swiglu = [_]u8{};\npub const ngen_swiglu128 = [_]u8{};\npub const ngen_a8 = [_]u8{};\npub const ngen_a8_swiglu = [_]u8{};\npub const ngen_a4 = [_]u8{};\npub const ngen_geglu = [_]u8{};\n"), .target = linux }); - const tail_linux = b.createModule(.{ .root_source_file = b.path("zig/src/xpu/tail_test.zig"), .target = linux, .optimize = .ReleaseFast, .link_libc = true, .imports = &.{ .{ .name = "ze", .module = ze_linux }, .{ .name = "xpu_tp", .module = tp_linux }, .{ .name = "core", .module = core_linux }, .{ .name = "xpu_qwen27_kernels", .module = empty_linux } } }); + const device_linux = b.createModule(.{ .root_source_file = b.path("zig/src/xpu/device_id.zig"), .target = linux, .optimize = .ReleaseFast, .link_libc = true, .imports = &.{.{ .name = "ze", .module = ze_linux }} }); + const tail_linux = b.createModule(.{ .root_source_file = b.path("zig/src/xpu/tail_test.zig"), .target = linux, .optimize = .ReleaseFast, .link_libc = true, .imports = &.{ .{ .name = "ze", .module = ze_linux }, .{ .name = "xpu_tp", .module = tp_linux }, .{ .name = "core", .module = core_linux }, .{ .name = "xpu_qwen27_kernels", .module = empty_linux }, .{ .name = "device_id", .module = device_linux } } }); b.step("compile-xpu-qwen27-tail-linux", "Cross-compile the XPU 27B prompt-tail device check for Linux").dependOn(&b.addExecutable(.{ .name = "tf-xpu-qwen27-tail-test", .root_module = tail_linux }).step); } From 85fca012b950148276b275dfa55369f8a6627f7b Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Tue, 24 Nov 2026 16:40:23 +0000 Subject: [PATCH 07/11] changelog: #4802 under Unreleased --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index bbcc33fd435..89e49c62787 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 +- Qwen 3.8-27B on XPU: Arc Pro B60 cards open through device detection when no B70 is found; explicit overrides and the B70 default are unchanged (#4802). + - Tools: `tools/bench_prose.py` measures decode on distinct natural prose, cache-format loss and long-context recall against any server, and counts a result only with matching token evidence (#4797). Thanks @GrgaPalcic. - GLM Metal: one-Mac GLM-5.3-Flash prefills short remaining work first by default, cutting a short reply beside a long prompt from 6.11 s to 3.56 s (41.7%) with long-prompt TTFT within 1.2% (#3903, refs #3152). Thanks to @gilby. From ac856acadfd41ec6e2fec483960a7c22f9cff631 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Mon, 23 Nov 2026 22:15:43 +0000 Subject: [PATCH 08/11] inkling2 metal: routed experts and combine one thread an output, each dot the serial chain Each expert product ran one 32-thread group a route pair, its lanes looping over the pair's outputs: 36 outputs a lane for GU (n 1152), 72 for down (n 2304), and eight groups a decode step. Combine ran one group a token. The four products and the combine now launch threadgroups along the outputs by route pairs (or tokens), one thread an output. Each thread runs the same ink2_dot_nv / ink2_dot_mx as before: one FP32 chain from column 0 up, every product rounded before its add (fp contract off), then the same BF16 rounding and activation. Combine keeps its ascending-expert loop. Only which thread computes an output changes, so every output is bit-identical to the serial reference. Threads past the row return before any read. Launches stay 32 threads, so the existing records hold; the quantize kernels are unchanged. The grid of outputs by route pairs and launchGrid follow #4448's 2f386ca16fc2; its lane-strided partial sums and simd_sum, which change the FP32 sum order, are not taken. Tests: test-inkling2-controls-host checks the source keeps both dots serial with no simd_sum and launches every product and the combine one output a thread (fails before: five lane loops), and that the grid covers every output exactly once, with no thread past the row reading. The block count rounds up as n / 32 plus one for a remainder, so the largest u32 widths (4294967265 through 4294967295) take 134217728 blocks instead of overflowing n + 31; a test asserts those widths and fails on the n + 31 form. Co-authored-by: Seth For Privacy <40500387+sethforprivacy@users.noreply.github.com> --- zig/build/kernel_contract.zig | 1 + zig/kernels/metal/inkling2/experts.metal | 77 ++++++++++--------- zig/src/families/inkling2/metal/experts.zig | 18 +++-- .../families/inkling2/metal/experts_plan.zig | 21 ++++- .../families/inkling2/metal/experts_test.zig | 5 +- .../metal_inkling2_experts_controls.zig | 48 +++++++++++- 6 files changed, 125 insertions(+), 45 deletions(-) diff --git a/zig/build/kernel_contract.zig b/zig/build/kernel_contract.zig index f763661d93d..175051390ca 100644 --- a/zig/build/kernel_contract.zig +++ b/zig/build/kernel_contract.zig @@ -38,6 +38,7 @@ pub fn hostTests(b: *std.Build, family: *std.Build.Step) void { .{ .name = "inkling2_glue_plan", .module = b.createModule(.{ .root_source_file = b.path("zig/src/families/inkling2/metal/glue_plan.zig") }) }, .{ .name = "inkling2_loop_plan", .module = b.createModule(.{ .root_source_file = b.path("zig/src/families/inkling2/metal/loop_plan.zig") }) }, .{ .name = "inkling2_runtime_plan", .module = b.createModule(.{ .root_source_file = b.path("zig/src/families/inkling2/metal/runtime_plan.zig") }) }, + .{ .name = "inkling2_experts_plan", .module = b.createModule(.{ .root_source_file = b.path("zig/src/families/inkling2/metal/experts_plan.zig") }) }, }, }) })); b.step("test-inkling2-controls-host", "Inkling 2 Mini source controls plant one fault without a Metal compiler").dependOn(&inkling_controls.step); diff --git a/zig/kernels/metal/inkling2/experts.metal b/zig/kernels/metal/inkling2/experts.metal index b1ba70059cf..8995067ab31 100644 --- a/zig/kernels/metal/inkling2/experts.metal +++ b/zig/kernels/metal/inkling2/experts.metal @@ -69,37 +69,39 @@ inline bfloat ink2_act(float gate_dot, float up_dot) { device const uchar* S [[buffer(2)]], device const float* amax [[buffer(3)]], device const float* denominator [[buffer(4)]], device const int* ids [[buffer(5)]], device bfloat* Y [[buffer(6)]], constant Ink2MatrixArgs& a [[buffer(7)]], - uint group [[threadgroup_position_in_grid]], uint lane [[thread_index_in_threadgroup]]) { + uint2 tg [[threadgroup_position_in_grid]], uint lane [[thread_index_in_threadgroup]]) { + // One thread an output: threadgroup x is 32 outputs, y the route pair; each dot is the serial chain above. + const uint n = tg.x * 32u + lane, group = tg.y; + if (n >= a.n) return; const uint token = group / a.topk, expert = uint(ids[group]); const ulong expert_w = ulong(expert) * 2u * a.n * (a.k / 2u); const ulong expert_s = ulong(expert) * 2u * a.n * (a.k / 16u); const float phi = ink2_phi(amax, denominator, expert); - for (uint n = lane; n < a.n; n += 32u) { - const uint gr = 2u * n, ur = gr + 1u; - const float g = ink2_dot_nv(W + expert_w + ulong(gr) * (a.k / 2u), - S + expert_s + ulong(gr) * (a.k / 16u), X + ulong(token) * a.k, phi, a.k); - const float u = ink2_dot_nv(W + expert_w + ulong(ur) * (a.k / 2u), - S + expert_s + ulong(ur) * (a.k / 16u), X + ulong(token) * a.k, phi, a.k); - Y[group * a.n + n] = ink2_act(g, u); - } + const uint gr = 2u * n, ur = gr + 1u; + const float g = ink2_dot_nv(W + expert_w + ulong(gr) * (a.k / 2u), + S + expert_s + ulong(gr) * (a.k / 16u), X + ulong(token) * a.k, phi, a.k); + const float u = ink2_dot_nv(W + expert_w + ulong(ur) * (a.k / 2u), + S + expert_s + ulong(ur) * (a.k / 16u), X + ulong(token) * a.k, phi, a.k); + Y[group * a.n + n] = ink2_act(g, u); } [[kernel, max_total_threads_per_threadgroup(32)]] void tf_ink2_mxfp8_gu( device const bfloat* X [[buffer(0)]], device const uchar* W [[buffer(1)]], device const uchar* S [[buffer(2)]], device const int* ids [[buffer(3)]], device bfloat* Y [[buffer(4)]], constant Ink2MatrixArgs& a [[buffer(5)]], - uint group [[threadgroup_position_in_grid]], uint lane [[thread_index_in_threadgroup]]) { + uint2 tg [[threadgroup_position_in_grid]], uint lane [[thread_index_in_threadgroup]]) { + // One thread an output: threadgroup x is 32 outputs, y the route pair; each dot is the serial chain above. + const uint n = tg.x * 32u + lane, group = tg.y; + if (n >= a.n) return; const uint token = group / a.topk, expert = uint(ids[group]); const ulong expert_w = ulong(expert) * 2u * a.n * a.k; const ulong expert_s = ulong(expert) * 2u * a.n * (a.k / 32u); - for (uint n = lane; n < a.n; n += 32u) { - const uint gr = 2u * n, ur = gr + 1u; - const float g = ink2_dot_mx(W + expert_w + ulong(gr) * a.k, - S + expert_s + ulong(gr) * (a.k / 32u), X + ulong(token) * a.k, a.k); - const float u = ink2_dot_mx(W + expert_w + ulong(ur) * a.k, - S + expert_s + ulong(ur) * (a.k / 32u), X + ulong(token) * a.k, a.k); - Y[group * a.n + n] = ink2_act(g, u); - } + const uint gr = 2u * n, ur = gr + 1u; + const float g = ink2_dot_mx(W + expert_w + ulong(gr) * a.k, + S + expert_s + ulong(gr) * (a.k / 32u), X + ulong(token) * a.k, a.k); + const float u = ink2_dot_mx(W + expert_w + ulong(ur) * a.k, + S + expert_s + ulong(ur) * (a.k / 32u), X + ulong(token) * a.k, a.k); + Y[group * a.n + n] = ink2_act(g, u); } [[kernel, max_total_threads_per_threadgroup(32)]] void tf_ink2_nvfp4_down( @@ -107,27 +109,31 @@ inline bfloat ink2_act(float gate_dot, float up_dot) { device const uchar* S [[buffer(2)]], device const float* amax [[buffer(3)]], device const float* denominator [[buffer(4)]], device const int* ids [[buffer(5)]], device bfloat* Y [[buffer(6)]], constant Ink2MatrixArgs& a [[buffer(7)]], - uint group [[threadgroup_position_in_grid]], uint lane [[thread_index_in_threadgroup]]) { + uint2 tg [[threadgroup_position_in_grid]], uint lane [[thread_index_in_threadgroup]]) { + // One thread an output: threadgroup x is 32 outputs, y the route pair; each dot is the serial chain above. + const uint n = tg.x * 32u + lane, group = tg.y; + if (n >= a.n) return; const uint expert = uint(ids[group]); const ulong expert_w = ulong(expert) * a.n * (a.k / 2u); const ulong expert_s = ulong(expert) * a.n * (a.k / 16u); const float phi = ink2_phi(amax, denominator, expert); - for (uint n = lane; n < a.n; n += 32u) - Y[group * a.n + n] = bfloat(ink2_dot_nv(W + expert_w + ulong(n) * (a.k / 2u), - S + expert_s + ulong(n) * (a.k / 16u), X + ulong(group) * a.k, phi, a.k)); + Y[group * a.n + n] = bfloat(ink2_dot_nv(W + expert_w + ulong(n) * (a.k / 2u), + S + expert_s + ulong(n) * (a.k / 16u), X + ulong(group) * a.k, phi, a.k)); } [[kernel, max_total_threads_per_threadgroup(32)]] void tf_ink2_mxfp8_down( device const bfloat* X [[buffer(0)]], device const uchar* W [[buffer(1)]], device const uchar* S [[buffer(2)]], device const int* ids [[buffer(3)]], device bfloat* Y [[buffer(4)]], constant Ink2MatrixArgs& a [[buffer(5)]], - uint group [[threadgroup_position_in_grid]], uint lane [[thread_index_in_threadgroup]]) { + uint2 tg [[threadgroup_position_in_grid]], uint lane [[thread_index_in_threadgroup]]) { + // One thread an output: threadgroup x is 32 outputs, y the route pair; each dot is the serial chain above. + const uint n = tg.x * 32u + lane, group = tg.y; + if (n >= a.n) return; const uint expert = uint(ids[group]); const ulong expert_w = ulong(expert) * a.n * a.k; const ulong expert_s = ulong(expert) * a.n * (a.k / 32u); - for (uint n = lane; n < a.n; n += 32u) - Y[group * a.n + n] = bfloat(ink2_dot_mx(W + expert_w + ulong(n) * a.k, - S + expert_s + ulong(n) * (a.k / 32u), X + ulong(group) * a.k, a.k)); + Y[group * a.n + n] = bfloat(ink2_dot_mx(W + expert_w + ulong(n) * a.k, + S + expert_s + ulong(n) * (a.k / 32u), X + ulong(group) * a.k, a.k)); } // Weight decode helpers unpack checkpoint bytes and never quantize an activation. @@ -157,15 +163,16 @@ inline bfloat ink2_act(float gate_dot, float up_dot) { [[kernel, max_total_threads_per_threadgroup(32)]] void tf_ink2_combine( device const bfloat* down [[buffer(0)]], device const int* ids [[buffer(1)]], device const float* weights [[buffer(2)]], device bfloat* Y [[buffer(3)]], - constant Ink2MatrixArgs& a [[buffer(4)]], uint group [[threadgroup_position_in_grid]], + constant Ink2MatrixArgs& a [[buffer(4)]], uint2 tg [[threadgroup_position_in_grid]], uint lane [[thread_index_in_threadgroup]]) { + // One thread an output: threadgroup x is 32 outputs, y the token. + const uint n = tg.x * 32u + lane, group = tg.y; + if (n >= a.n) return; // Outer expert order, not route-slot order, fixes the reference's accumulation order. - for (uint n = lane; n < a.n; n += 32u) { - float sum = 0.0f; - for (uint expert = 0; expert < a.experts; ++expert) - for (uint slot = 0; slot < a.topk; ++slot) - if (uint(ids[group * a.topk + slot]) == expert) - sum += weights[group * a.topk + slot] * float(down[(group * a.topk + slot) * a.n + n]); - Y[group * a.n + n] = bfloat(sum); - } + float sum = 0.0f; + for (uint expert = 0; expert < a.experts; ++expert) + for (uint slot = 0; slot < a.topk; ++slot) + if (uint(ids[group * a.topk + slot]) == expert) + sum += weights[group * a.topk + slot] * float(down[(group * a.topk + slot) * a.n + n]); + Y[group * a.n + n] = bfloat(sum); } diff --git a/zig/src/families/inkling2/metal/experts.zig b/zig/src/families/inkling2/metal/experts.zig index 268ca0398ea..cb045e66a1c 100644 --- a/zig/src/families/inkling2/metal/experts.zig +++ b/zig/src/families/inkling2/metal/experts.zig @@ -58,13 +58,19 @@ fn launch(p: *const Pipelines, e: mtl.ComputeEncoder, op: Operation, groups: u32 e.dispatchGroups(mtl.Size.of(groups, 1, 1), mtl.Size.of(32, 1, 1)); } +/// The products and the combine: threadgroups along the outputs (x) by route pairs or tokens (y). +fn launchGrid(p: *const Pipelines, e: mtl.ComputeEncoder, op: Operation, g: plan.Geometry) void { + e.setPipeline(p.get(op)); + e.dispatchGroups(mtl.Size.of(g.blocks, g.groups, 1), mtl.Size.of(g.threads, 1, 1)); +} + /// Packed NVFP4 GU: X [rows,k], ids [rows,topk], Y [rows*topk,n]. pub fn nvfp4Gu(p: *const Pipelines, e: mtl.ComputeEncoder, x: Ref, w: Ref, scales: Ref, amax: Ref, denominator: Ref, ids: Ref, out: Ref, c: Call) !void { if (c.format != .nvfp4) return error.WrongExpertFormat; try plan.check(c); for ([_]Ref{ x, w, scales, amax, denominator, ids, out }, 0..) |b, i| e.setBuffer(b.buf, b.off, i); e.setValue(args(c), 7); - launch(p, e, .nvfp4_gu, plan.geometry(c).groups); + launchGrid(p, e, .nvfp4_gu, plan.geometry(c)); } /// Packed MXFP8 GU with UE8M0 scales per row/block32. @@ -73,7 +79,7 @@ pub fn mxfp8Gu(p: *const Pipelines, e: mtl.ComputeEncoder, x: Ref, w: Ref, scale try plan.check(c); for ([_]Ref{ x, w, scales, ids, out }, 0..) |b, i| e.setBuffer(b.buf, b.off, i); e.setValue(args(c), 5); - launch(p, e, .mxfp8_gu, plan.geometry(c).groups); + launchGrid(p, e, .mxfp8_gu, plan.geometry(c)); } pub fn nvfp4Down(p: *const Pipelines, e: mtl.ComputeEncoder, act: Ref, w: Ref, scales: Ref, amax: Ref, denominator: Ref, ids: Ref, out: Ref, c: Call) !void { @@ -81,7 +87,7 @@ pub fn nvfp4Down(p: *const Pipelines, e: mtl.ComputeEncoder, act: Ref, w: Ref, s try plan.check(c); for ([_]Ref{ act, w, scales, amax, denominator, ids, out }, 0..) |b, i| e.setBuffer(b.buf, b.off, i); e.setValue(args(c), 7); - launch(p, e, .nvfp4_down, plan.geometry(c).groups); + launchGrid(p, e, .nvfp4_down, plan.geometry(c)); } pub fn mxfp8Down(p: *const Pipelines, e: mtl.ComputeEncoder, act: Ref, w: Ref, scales: Ref, ids: Ref, out: Ref, c: Call) !void { @@ -89,7 +95,7 @@ pub fn mxfp8Down(p: *const Pipelines, e: mtl.ComputeEncoder, act: Ref, w: Ref, s try plan.check(c); for ([_]Ref{ act, w, scales, ids, out }, 0..) |b, i| e.setBuffer(b.buf, b.off, i); e.setValue(args(c), 5); - launch(p, e, .mxfp8_down, plan.geometry(c).groups); + launchGrid(p, e, .mxfp8_down, plan.geometry(c)); } /// Decode one expert matrix to BF16, not an activation quantization operation. @@ -112,8 +118,8 @@ pub fn combine(p: *const Pipelines, e: mtl.ComputeEncoder, down: Ref, ids: Ref, try plan.check(c); for ([_]Ref{ down, ids, weights, out }, 0..) |b, i| e.setBuffer(b.buf, b.off, i); e.setValue(args(c), 4); - // Combine has one group per token, rather than one per route pair. - launch(p, e, .combine, c.rows); + // Combine's rows are tokens, rather than route pairs. + launchGrid(p, e, .combine, plan.combineGeometry(c)); } pub fn gu(p: *const Pipelines, e: mtl.ComputeEncoder, x: Ref, w: Ref, scales: Ref, nv_globals: ?struct { amax: Ref, denominator: Ref }, ids: Ref, out: Ref, c: Call) !void { diff --git a/zig/src/families/inkling2/metal/experts_plan.zig b/zig/src/families/inkling2/metal/experts_plan.zig index 6b98f9fe18a..fcf0312dc0c 100644 --- a/zig/src/families/inkling2/metal/experts_plan.zig +++ b/zig/src/families/inkling2/metal/experts_plan.zig @@ -27,13 +27,32 @@ pub const Call = struct { format: Format, }; +/// Threadgroups of 32 threads, one an output: `blocks` along the outputs by `groups` route pairs (or tokens). pub const Geometry = struct { groups: u32, + blocks: u32, threads: u32 = 32, + + /// The output (block, lane) computes, or null past the row: each output is one thread's serial dot. + pub fn output(g: Geometry, n: u32, block: u32, lane: u32) ?u32 { + const at = block * g.threads + lane; + return if (at < n) at else null; + } }; +/// Threadgroups of 32 over `n` outputs, rounded up without overflowing at the largest u32 widths. +fn blocks(n: u32) u32 { + return n / 32 + @intFromBool(n % 32 != 0); +} + +/// A product's grid: every output of every route pair at once. pub fn geometry(c: Call) Geometry { - return .{ .groups = c.rows * c.topk }; + return .{ .groups = c.rows * c.topk, .blocks = blocks(c.n) }; +} + +/// The combine's grid: every output of every token at once. +pub fn combineGeometry(c: Call) Geometry { + return .{ .groups = c.rows, .blocks = blocks(c.n) }; } pub fn check(c: Call) !void { diff --git a/zig/src/families/inkling2/metal/experts_test.zig b/zig/src/families/inkling2/metal/experts_test.zig index 4ae2612b76f..6f503065b13 100644 --- a/zig/src/families/inkling2/metal/experts_test.zig +++ b/zig/src/families/inkling2/metal/experts_test.zig @@ -124,11 +124,14 @@ test "eight-term combine stress separates FP32 and BF16 in every contract order" try std.testing.expect(9.0 / exact_allowance >= 100); } -test "launch geometry is 32 scalar threads and validates block/layout edges" { +test "launch geometry is one thread an output over every route pair and validates block/layout edges" { const nv = p.Call{ .rows = 3, .k = 2304, .n = 1152, .format = .nvfp4 }; try p.check(nv); try std.testing.expectEqual(@as(u32, 24), p.geometry(nv).groups); + try std.testing.expectEqual(@as(u32, 36), p.geometry(nv).blocks); try std.testing.expectEqual(@as(u32, 32), p.geometry(nv).threads); + try std.testing.expectEqual(@as(u32, 3), p.combineGeometry(nv).groups); + try std.testing.expectEqual(@as(u32, 36), p.combineGeometry(nv).blocks); const mx = p.Call{ .rows = 1, .k = 1152, .n = 2304, .format = .mxfp8 }; try p.check(mx); var bad = nv; diff --git a/zig/tests/contract/metal_inkling2_experts_controls.zig b/zig/tests/contract/metal_inkling2_experts_controls.zig index e28ae1f9cd3..ad37be6fb2d 100644 --- a/zig/tests/contract/metal_inkling2_experts_controls.zig +++ b/zig/tests/contract/metal_inkling2_experts_controls.zig @@ -41,8 +41,8 @@ pub const Mutation = enum { .mx_down_scale => .{ .from = "S + expert_s + ulong(n) * (a.k / 32u), X + ulong(group) * a.k, a.k));", .to = "S + expert_s + ulong(n) * (a.k / 16u), X + ulong(group) * a.k, a.k));" }, .mx_decode_scale => .{ .from = "S[row * (a.k / 32u) + col / 32u]", .to = "S[row * (a.k / 32u) + col / 16u]" }, .combine_slot_order => .{ - .from = "for (uint expert = 0; expert < a.experts; ++expert)\n for (uint slot = 0; slot < a.topk; ++slot)\n if (uint(ids[group * a.topk + slot]) == expert)\n sum += weights[group * a.topk + slot] * float(down[(group * a.topk + slot) * a.n + n]);", - .to = "for (uint slot = 0; slot < a.topk; ++slot)\n sum += weights[group * a.topk + slot] * float(down[(group * a.topk + slot) * a.n + n]);", + .from = "for (uint expert = 0; expert < a.experts; ++expert)\n for (uint slot = 0; slot < a.topk; ++slot)\n if (uint(ids[group * a.topk + slot]) == expert)\n sum += weights[group * a.topk + slot] * float(down[(group * a.topk + slot) * a.n + n]);", + .to = "for (uint slot = 0; slot < a.topk; ++slot)\n sum += weights[group * a.topk + slot] * float(down[(group * a.topk + slot) * a.n + n]);", }, }; } @@ -81,3 +81,47 @@ test "expert source exports all seven entries and has no activation quantizer" { try std.testing.expect(std.mem.indexOf(u8, src.experts, "never quantize an activation") != null); try std.testing.expect(std.mem.indexOf(u8, src.experts, "e2m1(float") == null); } + +test "inkling2 experts: one thread an output, and each dot stays the serial chain in column order" { + const text = src.experts; + // no lane loops over outputs; four products and the combine each take one output a thread + try std.testing.expectEqual(@as(usize, 0), std.mem.count(u8, text, "for (uint n = lane; n < a.n; n += 32u)")); + try std.testing.expectEqual(@as(usize, 5), std.mem.count(u8, text, "const uint n = tg.x * 32u + lane")); + try std.testing.expectEqual(@as(usize, 5), std.mem.count(u8, text, "if (n >= a.n) return;")); + // the two dots: one FP32 chain from column 0 up, products rounded before each add, no lane reduction + try std.testing.expectEqual(@as(usize, 2), std.mem.count(u8, text, "for (uint c = 0; c < k; ++c)")); + try std.testing.expectEqual(@as(usize, 1), std.mem.count(u8, text, "#pragma METAL fp contract(off)")); + try std.testing.expectEqual(@as(usize, 0), std.mem.count(u8, text, "simd_sum")); +} + +test "inkling2 experts: every output is one thread's, exactly once, and threads past the row write nothing" { + const plan = @import("inkling2_experts_plan"); + for ([_]u32{ 1152, 2304, 33, 1 }) |n| { + const c = plan.Call{ .rows = 1, .k = 32, .n = n, .format = .mxfp8 }; + const grid = plan.geometry(c); + const seen = try std.testing.allocator.alloc(u8, n); + defer std.testing.allocator.free(seen); + @memset(seen, 0); + var idle: u32 = 0; + for (0..grid.blocks) |block| for (0..grid.threads) |lane| { + if (grid.output(n, @intCast(block), @intCast(lane))) |at| seen[at] += 1 else idle += 1; + }; + for (seen) |times| try std.testing.expectEqual(@as(u8, 1), times); + try std.testing.expect(idle < grid.threads); // only the last block has threads past the row + } +} + +test "inkling2 experts: block counts round up without overflow through the largest u32 width" { + const plan = @import("inkling2_experts_plan"); + const cases = [_][2]u32{ .{ 1, 1 }, .{ 32, 1 }, .{ 33, 2 }, .{ 4294967264, 134217727 }, .{ 4294967265, 134217728 }, .{ 4294967280, 134217728 }, .{ 4294967295, 134217728 } }; + for (cases) |case| { + const c = plan.Call{ .rows = 1, .k = 32, .n = case[0], .format = .mxfp8 }; + try std.testing.expectEqual(case[1], plan.geometry(c).blocks); + try std.testing.expectEqual(case[1], plan.combineGeometry(c).blocks); + // the last block reaches the last output, and none past it + const grid = plan.geometry(c); + const tail = (case[0] - 1) % 32; + try std.testing.expectEqual(@as(?u32, case[0] - 1), grid.output(case[0], grid.blocks - 1, tail)); + if (tail < 31) try std.testing.expectEqual(@as(?u32, null), grid.output(case[0], grid.blocks - 1, tail + 1)); + } +} From 02bee7f3d7f931eeb60e131eb3b20a3cf4a73c78 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Tue, 24 Nov 2026 11:04:12 +0000 Subject: [PATCH 09/11] inkling2 metal contract: the expert grid byte for byte against main's kernels The contract's expert cells ran products of at most 12 outputs a pair and combines of at most 12 a token, so only the first output block of the new grid ever ran, and they compared with a float64 bound, not with main's bytes. Each of the five operations the grid changed (NVFP4 and MXFP8 GU and down, and the combine) now has a cell that replaces main's kernel: main's experts.metal at 5e390519d0, frozen under baselines/, on main's own launch (one 32-thread group a route pair, a token for the combine, each lane looping over its outputs). On the same inputs, every output byte of the new grid must equal main's. The shapes are several output blocks with tails (n 65, 64, 63 and the 1, 31, 32, 33 edges), Mini's own widths (GU k 2304 n 1152, down k 1152 n 2304, combine n 2304) and 64 rows (128 route pairs). The float64 reference now holds dots of 2304 terms. Two planted grid faults go into all five kernels, each a control at the shapes gate: every output block past the first returning before it writes, and the pair (token) index halved so two pairs write one row. --- .../baselines/inkling2_experts_main.metal.txt | 171 ++++++++++++++++++ zig/tests/contract/metal_inkling2_experts.zig | 151 +++++++++++++++- .../metal_inkling2_experts_controls.zig | 10 + 3 files changed, 323 insertions(+), 9 deletions(-) create mode 100644 zig/tests/contract/baselines/inkling2_experts_main.metal.txt diff --git a/zig/tests/contract/baselines/inkling2_experts_main.metal.txt b/zig/tests/contract/baselines/inkling2_experts_main.metal.txt new file mode 100644 index 00000000000..b1ba70059cf --- /dev/null +++ b/zig/tests/contract/baselines/inkling2_experts_main.metal.txt @@ -0,0 +1,171 @@ +// Inkling 2 Mini M3: packed weight decode in registers, BF16 activations, FP32 reductions. +#include +using namespace metal; +#pragma METAL fp contract(off) + +struct Ink2MatrixArgs { uint k, n, topk, experts; }; +struct Ink2DecodeArgs { uint rows, k; }; + +inline float ink2_e2m1(uint code) { + const float magnitude[8] = {0.0f, 0.5f, 1.0f, 1.5f, 2.0f, 3.0f, 4.0f, 6.0f}; + const float v = magnitude[code & 7u]; + return (code & 8u) ? -v : v; +} + +inline float ink2_e4m3(uint code) { + const uint exp = (code >> 3u) & 15u, mant = code & 7u; + if (exp == 15u && mant == 7u) return NAN; + const float v = exp ? ldexp(1.0f + float(mant) * 0.125f, int(exp) - 7) + : float(mant) * (1.0f / 512.0f); + return (code & 0x80u) ? -v : v; +} + +inline float ink2_phi(device const float* amax, device const float* denominator, uint expert) { + // Loader casts both globals to BF16 before the dequantization operation. + return precise::divide(float(bfloat(amax[expert])), float(bfloat(denominator[0]))); +} + +inline float ink2_nv_weight(uchar packed, uint column, uchar scale, float phi) { + const uint code = (column & 1u) ? uint(packed >> 4u) : uint(packed & 15u); + const float inner = ink2_e2m1(code) * ink2_e4m3(scale); + return float(bfloat(inner * phi)); +} + +inline float ink2_mx_weight(uchar value, uchar scale) { + const float w = ldexp(ink2_e4m3(value), int(scale) - 127); + // E4M3 times a power of two is exactly representable in BF16, still round explicitly. + return float(bfloat(w)); +} + +inline float ink2_dot_nv(device const uchar* w, device const uchar* scales, + device const bfloat* x, float phi, uint k) { + float sum = 0.0f; + for (uint c = 0; c < k; ++c) + sum += ink2_nv_weight(w[c / 2u], c, scales[c / 16u], phi) * float(x[c]); + return sum; +} + +inline float ink2_dot_mx(device const uchar* w, device const uchar* scales, + device const bfloat* x, uint k) { + float sum = 0.0f; + for (uint c = 0; c < k; ++c) + sum += ink2_mx_weight(w[c], scales[c / 32u]) * float(x[c]); + return sum; +} + +inline float ink2_cap(float x, float cap) { + return cap * precise::tanh(precise::divide(x, cap)); +} + +inline bfloat ink2_act(float gate_dot, float up_dot) { + const float gate = float(bfloat(gate_dot)), up = float(bfloat(up_dot)); + const float left = ink2_cap(gate, 4.0f) * precise::divide(1.0f, 1.0f + precise::exp(-gate)); + // Both GEMM results round before the softcapped SwiGLU; sigmoid uses the rounded gate. + return bfloat(left * ink2_cap(up, 25.0f)); +} + +[[kernel, max_total_threads_per_threadgroup(32)]] void tf_ink2_nvfp4_gu( + device const bfloat* X [[buffer(0)]], device const uchar* W [[buffer(1)]], + device const uchar* S [[buffer(2)]], device const float* amax [[buffer(3)]], + device const float* denominator [[buffer(4)]], device const int* ids [[buffer(5)]], + device bfloat* Y [[buffer(6)]], constant Ink2MatrixArgs& a [[buffer(7)]], + uint group [[threadgroup_position_in_grid]], uint lane [[thread_index_in_threadgroup]]) { + const uint token = group / a.topk, expert = uint(ids[group]); + const ulong expert_w = ulong(expert) * 2u * a.n * (a.k / 2u); + const ulong expert_s = ulong(expert) * 2u * a.n * (a.k / 16u); + const float phi = ink2_phi(amax, denominator, expert); + for (uint n = lane; n < a.n; n += 32u) { + const uint gr = 2u * n, ur = gr + 1u; + const float g = ink2_dot_nv(W + expert_w + ulong(gr) * (a.k / 2u), + S + expert_s + ulong(gr) * (a.k / 16u), X + ulong(token) * a.k, phi, a.k); + const float u = ink2_dot_nv(W + expert_w + ulong(ur) * (a.k / 2u), + S + expert_s + ulong(ur) * (a.k / 16u), X + ulong(token) * a.k, phi, a.k); + Y[group * a.n + n] = ink2_act(g, u); + } +} + +[[kernel, max_total_threads_per_threadgroup(32)]] void tf_ink2_mxfp8_gu( + device const bfloat* X [[buffer(0)]], device const uchar* W [[buffer(1)]], + device const uchar* S [[buffer(2)]], device const int* ids [[buffer(3)]], + device bfloat* Y [[buffer(4)]], constant Ink2MatrixArgs& a [[buffer(5)]], + uint group [[threadgroup_position_in_grid]], uint lane [[thread_index_in_threadgroup]]) { + const uint token = group / a.topk, expert = uint(ids[group]); + const ulong expert_w = ulong(expert) * 2u * a.n * a.k; + const ulong expert_s = ulong(expert) * 2u * a.n * (a.k / 32u); + for (uint n = lane; n < a.n; n += 32u) { + const uint gr = 2u * n, ur = gr + 1u; + const float g = ink2_dot_mx(W + expert_w + ulong(gr) * a.k, + S + expert_s + ulong(gr) * (a.k / 32u), X + ulong(token) * a.k, a.k); + const float u = ink2_dot_mx(W + expert_w + ulong(ur) * a.k, + S + expert_s + ulong(ur) * (a.k / 32u), X + ulong(token) * a.k, a.k); + Y[group * a.n + n] = ink2_act(g, u); + } +} + +[[kernel, max_total_threads_per_threadgroup(32)]] void tf_ink2_nvfp4_down( + device const bfloat* X [[buffer(0)]], device const uchar* W [[buffer(1)]], + device const uchar* S [[buffer(2)]], device const float* amax [[buffer(3)]], + device const float* denominator [[buffer(4)]], device const int* ids [[buffer(5)]], + device bfloat* Y [[buffer(6)]], constant Ink2MatrixArgs& a [[buffer(7)]], + uint group [[threadgroup_position_in_grid]], uint lane [[thread_index_in_threadgroup]]) { + const uint expert = uint(ids[group]); + const ulong expert_w = ulong(expert) * a.n * (a.k / 2u); + const ulong expert_s = ulong(expert) * a.n * (a.k / 16u); + const float phi = ink2_phi(amax, denominator, expert); + for (uint n = lane; n < a.n; n += 32u) + Y[group * a.n + n] = bfloat(ink2_dot_nv(W + expert_w + ulong(n) * (a.k / 2u), + S + expert_s + ulong(n) * (a.k / 16u), X + ulong(group) * a.k, phi, a.k)); +} + +[[kernel, max_total_threads_per_threadgroup(32)]] void tf_ink2_mxfp8_down( + device const bfloat* X [[buffer(0)]], device const uchar* W [[buffer(1)]], + device const uchar* S [[buffer(2)]], device const int* ids [[buffer(3)]], + device bfloat* Y [[buffer(4)]], constant Ink2MatrixArgs& a [[buffer(5)]], + uint group [[threadgroup_position_in_grid]], uint lane [[thread_index_in_threadgroup]]) { + const uint expert = uint(ids[group]); + const ulong expert_w = ulong(expert) * a.n * a.k; + const ulong expert_s = ulong(expert) * a.n * (a.k / 32u); + for (uint n = lane; n < a.n; n += 32u) + Y[group * a.n + n] = bfloat(ink2_dot_mx(W + expert_w + ulong(n) * a.k, + S + expert_s + ulong(n) * (a.k / 32u), X + ulong(group) * a.k, a.k)); +} + +// Weight decode helpers unpack checkpoint bytes and never quantize an activation. +[[kernel, max_total_threads_per_threadgroup(32)]] void tf_ink2_nvfp4_quantize( + device const uchar* W [[buffer(0)]], device const uchar* S [[buffer(1)]], + device const float* amax [[buffer(2)]], device const float* denominator [[buffer(3)]], + device bfloat* Y [[buffer(4)]], constant Ink2DecodeArgs& a [[buffer(5)]], + uint group [[threadgroup_position_in_grid]], uint lane [[thread_index_in_threadgroup]]) { + const uint at = group * 32u + lane; + if (at >= a.rows * a.k) return; + const uint row = at / a.k, col = at % a.k; + const float phi = ink2_phi(amax, denominator, 0); + Y[at] = bfloat(ink2_nv_weight(W[row * (a.k / 2u) + col / 2u], col, + S[row * (a.k / 16u) + col / 16u], phi)); +} + +[[kernel, max_total_threads_per_threadgroup(32)]] void tf_ink2_mxfp8_quantize( + device const uchar* W [[buffer(0)]], device const uchar* S [[buffer(1)]], + device bfloat* Y [[buffer(2)]], constant Ink2DecodeArgs& a [[buffer(3)]], + uint group [[threadgroup_position_in_grid]], uint lane [[thread_index_in_threadgroup]]) { + const uint at = group * 32u + lane; + if (at >= a.rows * a.k) return; + const uint row = at / a.k, col = at % a.k; + Y[at] = bfloat(ink2_mx_weight(W[at], S[row * (a.k / 32u) + col / 32u])); +} + +[[kernel, max_total_threads_per_threadgroup(32)]] void tf_ink2_combine( + device const bfloat* down [[buffer(0)]], device const int* ids [[buffer(1)]], + device const float* weights [[buffer(2)]], device bfloat* Y [[buffer(3)]], + constant Ink2MatrixArgs& a [[buffer(4)]], uint group [[threadgroup_position_in_grid]], + uint lane [[thread_index_in_threadgroup]]) { + // Outer expert order, not route-slot order, fixes the reference's accumulation order. + for (uint n = lane; n < a.n; n += 32u) { + float sum = 0.0f; + for (uint expert = 0; expert < a.experts; ++expert) + for (uint slot = 0; slot < a.topk; ++slot) + if (uint(ids[group * a.topk + slot]) == expert) + sum += weights[group * a.topk + slot] * float(down[(group * a.topk + slot) * a.n + n]); + Y[group * a.n + n] = bfloat(sum); + } +} diff --git a/zig/tests/contract/metal_inkling2_experts.zig b/zig/tests/contract/metal_inkling2_experts.zig index 55c9a3d1c66..39f5d23a935 100644 --- a/zig/tests/contract/metal_inkling2_experts.zig +++ b/zig/tests/contract/metal_inkling2_experts.zig @@ -1,4 +1,4 @@ -//! Inkling 2 Mini M3 contracts: independent FP64 decode/dot/activation and ascending-expert combine. +//! Inkling 2 Mini M3 contracts: FP64 decode/dot/activation, ascending-expert combine, and the grid against main. const std = @import("std"); const mtl = @import("metal"); const contract = @import("contract"); @@ -10,9 +10,41 @@ const rig_ = @import("rig.zig"); const host = @import("tensorfold").inkling2_metal_host.experts; const controls = @import("metal_inkling2_experts_controls.zig"); const src = @import("inkling2_metal"); +/// main's expert kernels (5e390519d0): a 32-thread group a route pair (combine: a token), lanes looping over outputs. +const frozen = @embedFile("baselines/inkling2_experts_main.metal.txt"); +/// main's Ink2MatrixArgs, as its launcher bound it. +const MainArgs = extern struct { k: u32, n: u32, topk: u32, experts: u32 }; pub const Kind = enum { nv_gu, nv_down, mx_gu, mx_down, nv_decode, mx_decode, combine }; +/// A cell: an entry or control against float64, or a grid operation against main's bytes, as is or with a grid fault. +pub const Variant = enum { + plain, + control, + grid, + grid_block, + grid_pair, + + fn isGrid(v: Variant) bool { + return v == .grid or v == .grid_block or v == .grid_pair; + } +}; + +/// The operations the output grid changed: the four products and the combine (the decodes keep their launch). +pub const grid_kinds = [_]Kind{ .nv_gu, .nv_down, .mx_gu, .mx_down, .combine }; + +fn operation(k: Kind) host.Operation { + return switch (k) { + .nv_gu => .nvfp4_gu, + .nv_down => .nvfp4_down, + .mx_gu => .mxfp8_gu, + .mx_down => .mxfp8_down, + .nv_decode => .nvfp4_quantize, + .mx_decode => .mxfp8_quantize, + .combine => .combine, + }; +} + fn symbol(k: Kind) []const u8 { return switch (k) { .nv_gu => "tf_ink2_nvfp4_gu", @@ -80,7 +112,37 @@ pub fn spec(k: Kind, control: bool) c.Spec { }; } +fn gridName(k: Kind, v: Variant) []const u8 { + const names: [3][]const u8 = switch (k) { + .nv_gu => .{ "metal inkling2 experts tf_ink2_nvfp4_gu grid against main", "control: metal inkling2 experts tf_ink2_nvfp4_gu output block dropped", "control: metal inkling2 experts tf_ink2_nvfp4_gu pair index halved" }, + .nv_down => .{ "metal inkling2 experts tf_ink2_nvfp4_down grid against main", "control: metal inkling2 experts tf_ink2_nvfp4_down output block dropped", "control: metal inkling2 experts tf_ink2_nvfp4_down pair index halved" }, + .mx_gu => .{ "metal inkling2 experts tf_ink2_mxfp8_gu grid against main", "control: metal inkling2 experts tf_ink2_mxfp8_gu output block dropped", "control: metal inkling2 experts tf_ink2_mxfp8_gu pair index halved" }, + .mx_down => .{ "metal inkling2 experts tf_ink2_mxfp8_down grid against main", "control: metal inkling2 experts tf_ink2_mxfp8_down output block dropped", "control: metal inkling2 experts tf_ink2_mxfp8_down pair index halved" }, + .combine => .{ "metal inkling2 experts tf_ink2_combine grid against main", "control: metal inkling2 experts tf_ink2_combine output block dropped", "control: metal inkling2 experts tf_ink2_combine token index halved" }, + .nv_decode, .mx_decode => unreachable, + }; + return names[if (v == .grid_block) 1 else if (v == .grid_pair) 2 else 0]; +} + +/// A grid cell: output blocks with tails, Mini's widths and 64 rows, every output byte against main's kernel. +pub fn gridSpec(k: Kind, v: Variant) c.Spec { + var s = spec(k, false); + s.name = gridName(k, v); + s.replaces = "main's kernel on its one-group-a-pair launch (5e390519d0)"; + // edges in the outputs a row: 1, 31, 32, 33 and the widest served + s.tiles = .{ .{}, .{ .size = 32 }, .{} }; + s.served = switch (k) { + .nv_gu, .mx_gu => &.{ .{ .rows = 2, .n = 65, .k = 64 }, .{ .rows = 1, .n = 1152, .k = 2304 }, .{ .rows = 64, .n = 33, .k = 32 }, .{ .rows = 3, .n = 64, .k = 32 } }, + .nv_down, .mx_down => &.{ .{ .rows = 2, .n = 65, .k = 64 }, .{ .rows = 1, .n = 2304, .k = 1152 }, .{ .rows = 64, .n = 33, .k = 32 }, .{ .rows = 3, .n = 63, .k = 32 } }, + .combine => &.{ .{ .rows = 2, .n = 65, .k = 8 }, .{ .rows = 4, .n = 2304, .k = 8 }, .{ .rows = 64, .n = 33, .k = 8 } }, + .nv_decode, .mx_decode => unreachable, + }; + return s; +} + const Sim = struct { acc: c.Accum, order: g.Order }; +/// The longest dot a cell's float64 reference holds: Mini's hidden width, GU's reduction. +const max_terms = 2304; const Sample = struct { value: f64, magnitude: f64 }; const Dot = struct { value: f64, magnitude: f64 }; @@ -90,6 +152,10 @@ pub const Probe = struct { pipes: host.Pipelines, kind: Kind, ctl: controls.Mutation, + variant: Variant = .plain, + /// main's kernels, for a grid cell's baseline, and the buffer main's launch writes. + base: ?host.Pipelines = null, + base_out: rig_.Ref = undefined, shape: c.Shape = undefined, x: []u16 = &.{}, w: []u8 = &.{}, @@ -103,7 +169,22 @@ pub const Probe = struct { pub fn init(a: std.mem.Allocator, device: mtl.Device, queue: mtl.Queue, kind: Kind, control: bool) !Probe { const text = try controls.apply(a, if (control) mutation(kind) else .none); defer a.free(text); - return .{ .a = a, .rig = .{ .a = a, .device = device, .queue = queue }, .pipes = try host.Pipelines.loadSource(device, text), .kind = kind, .ctl = if (control) mutation(kind) else .none }; + return .{ .a = a, .rig = .{ .a = a, .device = device, .queue = queue }, .pipes = try host.Pipelines.loadSource(device, text), .kind = kind, .ctl = if (control) mutation(kind) else .none, .variant = if (control) .control else .plain }; + } + + /// A grid cell: this tree's kernels (with a planted grid fault for a control) and main's frozen ones. + pub fn initGrid(a: std.mem.Allocator, device: mtl.Device, queue: mtl.Queue, kind: Kind, v: Variant) !Probe { + const m: controls.Mutation = switch (v) { + .grid_block => .grid_block_drop, + .grid_pair => .grid_pair_index, + else => .none, + }; + const text = try controls.apply(a, m); + defer a.free(text); + var pipes = try host.Pipelines.loadSource(device, text); + errdefer pipes.deinit(); + const base = try host.Pipelines.loadSource(device, frozen); + return .{ .a = a, .rig = .{ .a = a, .device = device, .queue = queue }, .pipes = pipes, .kind = kind, .ctl = m, .variant = v, .base = base }; } fn clear(p: *Probe) void { @@ -127,11 +208,13 @@ pub const Probe = struct { pub fn deinit(p: *Probe) void { p.clear(); p.pipes.deinit(); + if (p.base) |*base| base.deinit(); p.rig.deinit(); } pub fn kernel(p: *Probe) g.Kernel { - return .{ .spec = spec(p.kind, p.ctl != .none), .ctx = p, .vt = if (p.kind == .combine and p.ctl == .combine_slot_order) &vt_exact else &vt, .control = p.ctl.gate() }; + const s = if (p.variant.isGrid()) gridSpec(p.kind, p.variant) else spec(p.kind, p.ctl != .none); + return .{ .spec = s, .ctx = p, .vt = if (p.kind == .combine and p.ctl == .combine_slot_order) &vt_exact else &vt, .control = p.ctl.gate() }; } const vt = blk: { var table = g.hooks(Probe); @@ -146,11 +229,14 @@ pub const Probe = struct { pub fn prepare(p: *Probe, shape: c.Shape, fill: g.Fill, seed: u64) !bool { const k = p.kind; - if (shape.rows == 0 or shape.rows > 8) return false; - if (isGu(k) and (shape.n > 8 or shape.k > 64 or shape.k % 32 != 0)) return false; - if (isDown(k) and (shape.n > 12 or shape.k > 64 or shape.k % 32 != 0)) return false; + // a grid cell reaches Mini's widths and 64 rows; the float64 cells stay small + const grid = p.variant.isGrid(); + if (shape.rows == 0 or shape.rows > @as(usize, if (grid) 64 else 8)) return false; + const max_k: usize = if (grid) max_terms else 64; + if (isGu(k) and (shape.n > @as(usize, if (grid) 1152 else 8) or shape.k > max_k or shape.k % 32 != 0)) return false; + if (isDown(k) and (shape.n > @as(usize, if (grid) 2304 else 12) or shape.k > max_k or shape.k % 32 != 0)) return false; if (isDecode(k) and (shape.n != shape.k or shape.k > 64 or shape.k % 32 != 0)) return false; - if (k == .combine and (shape.n > 12 or shape.k != 8)) return false; + if (k == .combine and (shape.n > @as(usize, if (grid) 2304 else 12) or shape.k != 8)) return false; p.clear(); p.shape = shape; const nv = isNv(k); @@ -247,9 +333,29 @@ pub const Probe = struct { p.refs[4] = out; } } + if (grid) p.base_out = try p.rig.scratch(p.count() * 2); return true; } + /// main's bytes on the prepared inputs: its frozen kernel on its own launch, into a buffer poisoned as the output. + pub fn replaced(p: *Probe) ![]const u8 { + const base = p.base orelse return error.NoBaseline; + const len = p.count() * 2; + @memset(p.rig.bytes(p.base_out, len), 0xff); + const bound: usize = if (p.kind == .combine) 4 else if (isNv(p.kind)) 7 else 5; + const c_ = p.call(); + const pass = p.rig.begin(); + const e = pass.e; + e.setPipeline(base.entries[@backingInt(operation(p.kind))]); + for (p.refs[0 .. bound - 1], 0..) |r, i| e.setBuffer(r.buf, r.off, i); + e.setBuffer(p.base_out.buf, p.base_out.off, bound - 1); + e.setValue(MainArgs{ .k = c_.k, .n = c_.n, .topk = c_.topk, .experts = c_.experts }, bound); + const groups = if (p.kind == .combine) c_.rows else c_.rows * c_.topk; + e.dispatchGroups(mtl.Size.of(groups, 1, 1), mtl.Size.of(32, 1, 1)); + try p.rig.finish(pass); + return p.rig.bytes(p.base_out, len); + } + fn hr(b: rig_.Ref) host.Ref { return .{ .buf = b.buf, .off = b.off }; } @@ -301,7 +407,8 @@ pub const Probe = struct { } fn dot(p: *const Probe, expert: usize, row: usize, x: []const u16, sim: ?Sim) Dot { - var terms: [64]f64 = undefined; + var terms: [max_terms]f64 = undefined; + std.debug.assert(p.shape.k <= max_terms); var magnitude: f64 = 0; for (0..p.shape.k) |col| { const term = p.weight(expert, row, col) * @as(f64, c.fromBf16(x[col])); @@ -382,7 +489,7 @@ pub const Suite = struct { device: mtl.Device, queue: mtl.Queue, kernels: *std.ArrayList(g.Kernel), - probes: [14]Probe = undefined, + probes: [std.enums.values(Kind).len * 2 + grid_kinds.len * 3]Probe = undefined, made: usize = 0, pub fn deinit(s: *Suite) void { @@ -397,9 +504,35 @@ pub const Suite = struct { s.made += 1; try s.kernels.append(s.a, s.probes[s.made - 1].kernel()); }; + for (grid_kinds) |kind| for ([_]Variant{ .grid, .grid_block, .grid_pair }) |v| { + if (only) |needle| if (std.mem.indexOf(u8, gridSpec(kind, v).name, needle) == null) continue; + s.probes[s.made] = try Probe.initGrid(s.a, s.device, s.queue, kind, v); + s.made += 1; + try s.kernels.append(s.a, s.probes[s.made - 1].kernel()); + }; } }; +test "grid cells: the five changed operations, each against main, with two grid controls, under the experts filter" { + var names: [grid_kinds.len * 3][]const u8 = undefined; + var made: usize = 0; + for (grid_kinds) |kind| for ([_]Variant{ .grid, .grid_block, .grid_pair }) |v| { + const s = gridSpec(kind, v); + try std.testing.expect(s.replaces != null); + try std.testing.expect(std.mem.indexOf(u8, s.name, "metal inkling2 experts ") != null); + try std.testing.expect(std.mem.indexOf(u8, s.name, symbol(kind)) != null); + // several output blocks at a served shape, and Mini's own width + var widest: usize = 0; + for (s.served) |x| widest = @max(widest, x.n); + try std.testing.expect(s.served[0].n > 64 and widest >= 1152); + for (names[0..made]) |other| try std.testing.expect(!std.mem.eql(u8, other, s.name)); + names[made] = s.name; + made += 1; + }; + try std.testing.expect(std.mem.indexOf(u8, frozen, "for (uint n = lane; n < a.n; n += 32u)") != null); + try std.testing.expect(std.mem.indexOf(u8, frozen, "tg.x") == null); +} + test "contract labels resolve to the seven shipped entries" { for (std.enums.values(Kind)) |kind| { const name = spec(kind, false).name; diff --git a/zig/tests/contract/metal_inkling2_experts_controls.zig b/zig/tests/contract/metal_inkling2_experts_controls.zig index ad37be6fb2d..c2c32e0a7f4 100644 --- a/zig/tests/contract/metal_inkling2_experts_controls.zig +++ b/zig/tests/contract/metal_inkling2_experts_controls.zig @@ -12,6 +12,9 @@ pub const Mutation = enum { nv_decode_nibble, mx_decode_scale, combine_slot_order, + /// Grid faults, each in all five grid kernels; a grid cell's control runs one of them against main's bytes. + grid_block_drop, + grid_pair_index, pub fn name(m: Mutation) []const u8 { return switch (m) { @@ -23,6 +26,8 @@ pub const Mutation = enum { .nv_decode_nibble => "control: metal inkling2 experts tf_ink2_nvfp4_quantize nibble", .mx_decode_scale => "control: metal inkling2 experts tf_ink2_mxfp8_quantize scale", .combine_slot_order => "control: metal inkling2 experts tf_ink2_combine route-slot order", + .grid_block_drop => "control: metal inkling2 experts output block dropped", + .grid_pair_index => "control: metal inkling2 experts pair index halved", }; } @@ -44,6 +49,10 @@ pub const Mutation = enum { .from = "for (uint expert = 0; expert < a.experts; ++expert)\n for (uint slot = 0; slot < a.topk; ++slot)\n if (uint(ids[group * a.topk + slot]) == expert)\n sum += weights[group * a.topk + slot] * float(down[(group * a.topk + slot) * a.n + n]);", .to = "for (uint slot = 0; slot < a.topk; ++slot)\n sum += weights[group * a.topk + slot] * float(down[(group * a.topk + slot) * a.n + n]);", }, + // every output block past the first returns before writing: columns 32 on stay unwritten + .grid_block_drop => .{ .from = "if (n >= a.n) return;", .to = "if (n >= a.n || tg.x > 0u) return;" }, + // two route pairs (tokens) write one row, and the other stays unwritten + .grid_pair_index => .{ .from = "const uint n = tg.x * 32u + lane, group = tg.y;", .to = "const uint n = tg.x * 32u + lane, group = tg.y / 2u;" }, }; } }; @@ -53,6 +62,7 @@ pub fn apply(a: std.mem.Allocator, m: Mutation) ![]u8 { const change = m.edit(); const expected: usize = switch (m) { .nv_gu_up, .mx_gu_up, .nv_down_phi => 2, + .grid_block_drop, .grid_pair_index => 5, else => 1, }; if (std.mem.count(u8, src.experts, change.from) != expected) return error.ControlEditCount; From 3bf5a8208975ff50d814053bef821705f72f56b6 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Tue, 24 Nov 2026 13:46:58 +0000 Subject: [PATCH 10/11] changelog: inkling2 metal: routed experts and combine one thread an output, each dot the serial chain --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 89e49c62787..f16c6eaf373 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -37,6 +37,7 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel - OCR: `POST /ocr` now answers LiteParse's OCR server contract, with one text item per line and its box in page pixels (#2573). Thanks @laudney. +- Inkling 2 Mini on Metal: the routed experts and the combine run one thread per output with the same serial arithmetic, so one-stream decode is about 16x faster on an M5 Ultra and 17x on an M3 Ultra, with identical tokens (#4894). Thanks @sethforprivacy for the grid idea. - H3 on Metal: transformer products run on the `h3_gemm_32x64` kernel in 64-row bands and the decoder decodes 64 tiles a pass, with sums unchanged (#4641). From 559fe3ac0d7ff665e697c9f125e54486db2ef589 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Tue, 24 Nov 2026 16:40:26 +0000 Subject: [PATCH 11/11] changelog: #4894's line from lines/4894.txt in place of its own --- CHANGELOG.md | 9 ++------- 1 file changed, 2 insertions(+), 7 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index f16c6eaf373..e35a765d3fa 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,14 +4,14 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel ## Unreleased +- Inkling 2 Mini on Metal: the routed experts and the combine run one thread per output with the same serial arithmetic, so one-stream decode is about 16x faster on an M5 Ultra and 17x on an M3 Ultra, with identical tokens (#4894). Thanks @sethforprivacy for the grid idea. + - Qwen 3.8-27B on XPU: Arc Pro B60 cards open through device detection when no B70 is found; explicit overrides and the B70 default are unchanged (#4802). - Tools: `tools/bench_prose.py` measures decode on distinct natural prose, cache-format loss and long-context recall against any server, and counts a result only with matching token evidence (#4797). Thanks @GrgaPalcic. - GLM Metal: one-Mac GLM-5.3-Flash prefills short remaining work first by default, cutting a short reply beside a long prompt from 6.11 s to 3.56 s (41.7%) with long-prompt TTFT within 1.2% (#3903, refs #3152). Thanks to @gilby. - - - GLM on Metal: `GLM_ROUND_PROF` reports per-round host and GPU time sums (#3894). Thanks @gilby. - Server: `/v1/completions` takes OpenAI's legacy `echo`: the prompt's text, and with `logprobs` each prompt token's entry (`null` for the first), ahead of the reply's unchanged entries, for evaluation harnesses that score a prompt; `max_tokens: 0` with `echo` returns the prompt alone, and engines without `prompt_logprobs` refuse `echo` by name (#3526). @@ -30,15 +30,10 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel - Qwen3.8-27B on Metal: on M1-M4, a prompt that runs alone takes the prompt frame's rows per pass (512 by default, or `TF_PROMPT_ROWS`) instead of 128 when the prompt attention kernels build; a prompt beside a decoding request stays at 128 rows a pass before M5, and decoded spans, verifies and trees keep their 128-row limit (#2916, fixes #2907). - - - CUDA: an `sm_110` product target serves Qwen3.8-27B text on one Thor GPU (MLX 4-bit and NVFP4, with DFlash2) and refuses any other geometry (#4796). Thanks @IF-YFXJ. - OCR: `POST /ocr` now answers LiteParse's OCR server contract, with one text item per line and its box in page pixels (#2573). Thanks @laudney. - -- Inkling 2 Mini on Metal: the routed experts and the combine run one thread per output with the same serial arithmetic, so one-stream decode is about 16x faster on an M5 Ultra and 17x on an M3 Ultra, with identical tokens (#4894). Thanks @sethforprivacy for the grid idea. - - H3 on Metal: transformer products run on the `h3_gemm_32x64` kernel in 64-row bands and the decoder decodes 64 tiles a pass, with sums unchanged (#4641). - Hy4-flash: host-side weight map, TP=1/2/4 partition and Engram FP8 row codec for the official W8A16 FP8 checkpoint, with refusal tests; serving follows in later PRs (#4827). Thanks @GrgaPalcic.