diff --git a/CHANGELOG.md b/CHANGELOG.md index 33e5a2b8a16..ca07c3e0aa2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,11 +4,17 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel ## Unreleased -- Nemotron on HIP: a checkpoint whose token table (`backbone.embeddings`) is stored bf16 beside quantized matrices, marked `false` in config.json's quantization block or stored without scales, is admitted and loads; its rows are gathered as stored, the memory plan counts them at their stored bytes, and the startup label adds `+bf16-embed`; a bf16 `lm_head`, projection or other unquantized tensor is still refused by name (#3575, refs #3061). Thanks to @gilby. +- GLM-5.3-Flash on CUDA: while rank 0's vision tower encodes a prompt's images, the other ranks sleep on their liveness lines instead of waiting in a collective receive for the whole pass, so a long image pass no longer trips a net plugin's operation timeout and stops every rank; replies are unchanged (#3675, for #3614). Thanks to @ultradaoto. -- GLM-5.3-Flash on Metal: prompt index scores read each row's queries once per tile and routed-expert gathers load the next step's codes ahead, so follow-up turns reach the first token sooner with unchanged outputs (#3458). +- Desktop: a Qwen3.8-27B checkpoint is offered and loads, where the library applied the 2B geometry to every `qwen3_5` checkpoint and rejected the supported 27B at hidden size 5,120 (#3771). Thanks to @AIFlowML. + +- Intel Arc (XPU): two or four Level Zero GPUs open as peers in one context, with new peer-to-peer all-reduce collectives (FP16, BF16 and FP32; one shot up to 512 KiB, reduce-scatter then gather above) that sum in fixed rank order for exact bits, and `zig build xpu-tp-bench` builds `tf-xpu-tp-bench` to check and time them; nothing serves through them yet (#3585, part of #3583). Thanks to @supernovae. + +- Gemma 4 on Metal: an image input whose tower cannot load is refused cleanly instead of crashing during deinit, and a host test pins that a failed tower load leaves the model with none (#3421). Thanks to @jschmied. +- Nemotron on HIP: a checkpoint whose token table (`backbone.embeddings`) is stored bf16 beside quantized matrices, marked `false` in config.json's quantization block or stored without scales, is admitted and loads; its rows are gathered as stored, the memory plan counts them at their stored bytes, and the startup label adds `+bf16-embed`; a bf16 `lm_head`, projection or other unquantized tensor is still refused by name (#3575, refs #3061). Thanks to @gilby. +- GLM-5.3-Flash on Metal: prompt index scores read each row's queries once per tile and routed-expert gathers load the next step's codes ahead, so follow-up turns reach the first token sooner with unchanged outputs (#3458). - Web: an explicit relative `--token-file` path for the service installer is anchored to the directory it is run from, so the file the installer prepares and the file the generated launcher opens are the same; the default path and symlink handling are unchanged (#3838, fixes #3835). Thanks to @AIFlowML. @@ -38,8 +44,6 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel - Docs: the Qwen3.8-27B recipe says to serve with `--thinking-budget 4096` when thinking is on, and gives its GPQA Diamond result on TensorFold 1.2.7 and one GB10: replies cut at the limit from 78 of 198 to 0, and correct from 58.1% to 82.8% (#3373, fixes #3323). - - - Idol on CUDA: `tf-idol` runs Idol's denoiser on GB10 (sm_121) and on RTX 50-series and RTX PRO Blackwell (sm_120) cards against a reference case, gated step by step against idol-sdk's float32 run as on Metal, and refuses other GPUs by name (#1767, for #1757). Thanks to @jayleaton, with device runs from @GustavBlack and @Nipale-ai. - Docs: the drafter training recipe gains a section on adapting an already released drafter, budgeted from a few passes over the scarcest class at a low learning rate with early checkpoints, with the Qwen3.8-27B pilot behind it (#3369, refs #2667). Thanks to @Maxrio9. @@ -331,6 +335,7 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel - Flash Next at TP=2 on CUDA: the draft head, head-group and rollback passes replay as CUDA graphs on both ranks, and one-row split lanes skip their interleave copies; with Qwen3.8-Flash-Next NVFP4 and MTP at TP=2 on GB10s, decode is 1.2-1.4% faster and prompts 0.5-2.1% faster, with identical replies (#2837, for #2835). - Intel XPU: Qwen3.8-27B's prompt `gdn_out` kernel keeps its scale bookkeeping in cheaper exact forms, for 22.6% less kernel time on an Arc Pro B70 (736.3 to 570.2 ms over a 32K prompt) with byte-identical outputs, its fallback included (#2921, refs #2859). Thanks to @dinadur. - CI: the no-GPU host tests run as two parallel jobs, `zig` and `zig-b`, and a build check fails if any host check is in both or neither; a local `zig build test-host` still runs all of them (#3474). +- GLM-5.3-Flash on CUDA: while rank 0's vision tower encodes a prompt's images, the other ranks sleep on their liveness lines, as they do when no stream is left, instead of waiting in an NCCL receive for the whole pass, so a pass longer than a net plugin's operation timeout no longer stops every rank. On three GB10s at the mesh plugin's 30 s default, one 3840x2160 image (66 s), two 3072x1728 and fifteen 1920x1080 screenshots answer, with the same replies and short-image times (for #3614). - Nemotron 3.5 Bolt on CUDA: the shared expert runs on the side stream in decode windows, as on Super, so decode on a GB10 is 2.9-3.0% faster at one stream and 1.4-2.1% at four, with identical replies (#2847, for #2840). diff --git a/app/electron/agent/engine/geometry.ts b/app/electron/agent/engine/geometry.ts index a03b49bfc8b..3ac699088bc 100644 --- a/app/electron/agent/engine/geometry.ts +++ b/app/electron/agent/engine/geometry.ts @@ -40,6 +40,26 @@ const QWEN35: PinnedGeometry = { }, } +const QWEN27: PinnedGeometry = { + title: 'Qwen3.5 27B', + engineError: 'UnqualifiedQwenShape', + section: 'text_config', + dims: { + hidden_size: 5120, + vocab_size: 248320, + num_hidden_layers: 64, + intermediate_size: 17408, + linear_num_key_heads: 16, + linear_num_value_heads: 48, + linear_key_head_dim: 128, + linear_value_head_dim: 128, + linear_conv_kernel_dim: 4, + num_attention_heads: 24, + num_key_value_heads: 4, + head_dim: 256, + }, +} + const LFM2_MOE: PinnedGeometry = { title: 'LFM2.5', engineError: 'UnsupportedLfmGeometry', @@ -76,11 +96,15 @@ function layerTypesMatch(kind: string, layers: unknown): boolean { } export function admitGeometry(modelType: string, config: unknown): GeometryAdmission { - const pinned = PINNED[modelType] - if (!pinned) return { admitted: true, reason: null } + const defaultGeometry = PINNED[modelType] + if (!defaultGeometry) return { admitted: true, reason: null } if (!plain(config)) return { admitted: true, reason: null } - const section = pinned.section ? config[pinned.section] : config + const section = defaultGeometry.section ? config[defaultGeometry.section] : config if (!plain(section)) return { admitted: true, reason: null } + // The native dispatcher sends a tied head or the 2B hidden size to the 2B engine. + const useQwen27 = modelType === 'qwen3_5' && section.hidden_size === QWEN27.dims.hidden_size && + config.hidden_size !== QWEN35.dims.hidden_size && config.tie_word_embeddings !== true && section.tie_word_embeddings !== true + const pinned = useQwen27 ? QWEN27 : defaultGeometry for (const [key, expected] of Object.entries(pinned.dims)) { const value = section[key] if (value === undefined || value === null) continue @@ -91,7 +115,9 @@ export function admitGeometry(modelType: string, config: unknown): GeometryAdmis } } } - if (!layerTypesMatch(modelType, section.layer_types)) { + const interval = section.full_attention_interval + const wrongQwen27Interval = useQwen27 && typeof interval === 'number' && interval > 0 && interval !== 4 + if (wrongQwen27Interval || !layerTypesMatch(modelType, section.layer_types)) { return { admitted: false, reason: `This checkpoint's layer types are not the ones the bundled engine serves for ${pinned.title}; the engine refuses it (${pinned.engineError}).`, diff --git a/app/electron/agent/engine/library.test.ts b/app/electron/agent/engine/library.test.ts index 940c2b70a4b..5feee64a41f 100644 --- a/app/electron/agent/engine/library.test.ts +++ b/app/electron/agent/engine/library.test.ts @@ -200,6 +200,45 @@ try { const rescan = await lowMemory.scan() assert.deepEqual(rescan.models.map((model: any) => [model.id, model.loadable, model.reason]), lowered.models.map((model: any) => [model.id, model.loadable, model.reason]), 'a later rescan agrees with the refreshed state') + const qwen27 = { + hidden_size: 5120, vocab_size: 248320, num_hidden_layers: 64, intermediate_size: 17408, + linear_num_key_heads: 16, linear_num_value_heads: 48, linear_key_head_dim: 128, + linear_value_head_dim: 128, linear_conv_kernel_dim: 4, num_attention_heads: 24, + num_key_value_heads: 4, head_dim: 256, full_attention_interval: 4, + } + const qwen27Library = library({ appHome: path.join(root, 'qwen27-app') }) + const qwen27Models = path.join(root, 'qwen27-models') + const qwen27Cases = [ + { name: 'untied', tied: false, text: qwen27 }, + { name: 'wrong-kv-heads', tied: false, text: { ...qwen27, num_key_value_heads: 2 } }, + { name: 'wrong-interval', tied: false, text: { ...qwen27, full_attention_interval: 2 } }, + { name: 'tied-root', tied: true, text: qwen27 }, + { name: 'tied-tower', tied: false, text: { ...qwen27, tie_word_embeddings: true } }, + ] + for (const { name, tied, text } of qwen27Cases) { + const folder = path.join(qwen27Models, name) + await checkpoint(folder) + await fs.writeFile(path.join(folder, 'config.json'), JSON.stringify({ + model_type: 'qwen3_5', tie_word_embeddings: tied, quantization: { bits: 4, group_size: 64 }, + text_config: text, + })) + } + const qwen27Entries = (await qwen27Library.addFolder(qwen27Models)).models + const untied = qwen27Entries.find((model) => model.path === path.join(qwen27Models, 'untied'))! + assert.equal(untied.loadable, true, 'the qualified untied 27B is available in the library') + assert.equal((await qwen27Library.resolve(untied.id)).path, untied.path) + const wrongHeads = qwen27Entries.find((model) => model.path === path.join(qwen27Models, 'wrong-kv-heads'))! + assert.equal(wrongHeads.loadable, false) + assert.match(wrongHeads.reason!, /num key value heads is 2.*UnqualifiedQwenShape/) + const wrongInterval = qwen27Entries.find((model) => model.path === path.join(qwen27Models, 'wrong-interval'))! + assert.equal(wrongInterval.loadable, false) + assert.match(wrongInterval.reason!, /layer types/) + for (const name of ['tied-root', 'tied-tower']) { + const tied = qwen27Entries.find((model) => model.path === path.join(qwen27Models, name))! + assert.equal(tied.loadable, false) + assert.match(tied.reason!, /UnsupportedQwenGeometry/) + } + const validRegistry = await fs.readFile(lib.file, 'utf8') await fs.writeFile(lib.file, '{') await assert.rejects(() => library().snapshot(), /library is invalid/) diff --git a/zig/build/xpu.zig b/zig/build/xpu.zig index 85a9f272760..6195dc84e04 100644 --- a/zig/build/xpu.zig +++ b/zig/build/xpu.zig @@ -25,6 +25,7 @@ pub fn steps(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.buil .{ "gemm128", "zig/kernels/xpu/qwen27/gemm.cl", " -DGSZ=128" }, .{ "gdn", "zig/kernels/xpu/qwen27/gdn_chunk.cl", "" }, .{ "drafter", "zig/kernels/xpu/qwen27/drafter.cl", "" }, + .{ "tp", "zig/kernels/xpu/tp.cl", "" }, .{ "glue_g4s", "zig/kernels/xpu/gemma4/glue_g4.cl", " -I zig/kernels/xpu/gemma4" }, .{ "glue_g4g", "zig/kernels/xpu/gemma4/glue_g4.cl", " -DHD=512 -I zig/kernels/xpu/gemma4" }, .{ "rows_g4s", "zig/kernels/xpu/gemma4/glue_g4.cl", " -I zig/kernels/xpu/gemma4" }, @@ -94,9 +95,22 @@ 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 }); + 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 }); core.addImport("gpu_memory", @import("gpu_memory.zig").module(b, target)); + { + const embedded_tp = b.createModule(.{ .root_source_file = files.add("xpu_tp_kernels.zig", + \\pub const tp align(8) = @embedFile("tp.bin").*; + \\ + ) }); + 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); + 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); + } { const g4 = b.createModule(.{ .root_source_file = b.path("zig/src/families/gemma4/xpu_main.zig"), .target = target, .optimize = optimize, .link_libc = true }); g4.addImport("xpu_gemma4_kernels", embedded_g4); diff --git a/zig/build/xpu_contract.zig b/zig/build/xpu_contract.zig index c2c336df7a4..87e7389a606 100644 --- a/zig/build/xpu_contract.zig +++ b/zig/build/xpu_contract.zig @@ -24,6 +24,12 @@ pub fn steps(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.buil for ([_][]const u8{ "glue_attn.cl", "glue_quant.cl" }) |part| glue.addFileInput(b.path(b.fmt("zig/kernels/xpu/qwen27/{s}", .{part}))); const glue_dir = glue.addOutputDirectoryArg("ocloc-glue"); _ = files.addCopyFile(glue_dir.path(b, "glue.bin"), b.fmt("{s}/glue.bin", .{device})); + const tp_obj = b.addSystemCommand(&.{ ocloc, "compile", "-q", "-file" }); + tp_obj.addFileArg(b.path("zig/kernels/xpu/tp.cl")); + tp_obj.addArgs(&.{ "-device", device, "-options", opts, "-output_no_suffix", "-output", "tp", "-out_dir" }); + tp_obj.setCwd(b.path(".")); + const tp_dir = tp_obj.addOutputDirectoryArg("ocloc-tp"); + _ = files.addCopyFile(tp_dir.path(b, "tp.bin"), b.fmt("{s}/tp.bin", .{device})); const ctl = b.addSystemCommand(&.{ ocloc, "compile", "-q", "-file" }); ctl.addFileArg(b.path("zig/kernels/xpu/contract_controls.cl")); ctl.addArgs(&.{ "-device", device, "-options", opts, "-output_no_suffix", "-output", "contract_controls", "-out_dir" }); @@ -58,7 +64,7 @@ pub fn runner(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.bui const files = b.addWriteFiles(); if (prebuilt) |dir| { - for ([_][]const u8{ "glue", "contract_controls", "contract_gate_controls" }) |name| { + for ([_][]const u8{ "glue", "tp", "contract_controls", "contract_gate_controls" }) |name| { _ = files.addCopyFile(.{ .cwd_relative = b.fmt("{s}/{s}.bin", .{ dir, name }) }, b.fmt("{s}.bin", .{name})); } } else { @@ -70,17 +76,22 @@ pub fn runner(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.bui for ([_][]const u8{ "glue_attn.cl", "glue_quant.cl" }) |part| glue.addFileInput(b.path(b.fmt("zig/kernels/xpu/qwen27/{s}", .{part}))); const glue_dir = glue.addOutputDirectoryArg("ocloc-glue-run"); _ = files.addCopyFile(glue_dir.path(b, "glue.bin"), "glue.bin"); - for ([_][]const u8{ "contract_controls", "contract_gate_controls" }) |name| { + for ([_][2][]const u8{ + .{ "tp", "zig/kernels/xpu/tp.cl" }, + .{ "contract_controls", "zig/kernels/xpu/contract_controls.cl" }, + .{ "contract_gate_controls", "zig/kernels/xpu/contract_gate_controls.cl" }, + }) |pair| { const run = b.addSystemCommand(&.{ ocloc, "compile", "-q", "-file" }); - run.addFileArg(b.path(b.fmt("zig/kernels/xpu/{s}.cl", .{name}))); - run.addArgs(&.{ "-device", device, "-options", opts, "-output_no_suffix", "-output", name, "-out_dir" }); + run.addFileArg(b.path(pair[1])); + run.addArgs(&.{ "-device", device, "-options", opts, "-output_no_suffix", "-output", pair[0], "-out_dir" }); run.setCwd(b.path(".")); - const dir = run.addOutputDirectoryArg(b.fmt("ocloc-{s}-run", .{name})); - _ = files.addCopyFile(dir.path(b, b.fmt("{s}.bin", .{name})), b.fmt("{s}.bin", .{name})); + const dir = run.addOutputDirectoryArg(b.fmt("ocloc-{s}-run", .{pair[0]})); + _ = files.addCopyFile(dir.path(b, b.fmt("{s}.bin", .{pair[0]})), b.fmt("{s}.bin", .{pair[0]})); } } const images = b.createModule(.{ .root_source_file = files.add("xpu_contract_images.zig", \\pub const glue align(8) = @embedFile("glue.bin").*; + \\pub const tp align(8) = @embedFile("tp.bin").*; \\pub const controls align(8) = @embedFile("contract_controls.bin").*; \\pub const gate_controls align(8) = @embedFile("contract_gate_controls.bin").*; ), .target = target, .optimize = optimize }); diff --git a/zig/kernels/xpu/tp.cl b/zig/kernels/xpu/tp.cl new file mode 100644 index 00000000000..724f7378226 --- /dev/null +++ b/zig/kernels/xpu/tp.cl @@ -0,0 +1,154 @@ +// Level Zero P2P collectives for Intel Xe2: rank-ordered FP32 sums (#pragma OPENCL FP_CONTRACT OFF) for exact bits. +#pragma OPENCL FP_CONTRACT OFF +#pragma OPENCL EXTENSION cl_khr_fp16 : enable + +#define KERNEL(N) __attribute__((intel_reqd_sub_group_size(16))) __attribute__((reqd_work_group_size(N, 1, 1))) kernel + +static inline float bf2f(ushort h) { return as_float((uint)h << 16); } +static inline ushort f2bf(float f) { return intel_convert_bfloat16_as_ushort(f); } + +// 1-shot P2P AllReduce (FP16): out[i] = fp16_rte(p0[i] + p1[i]) +KERNEL(256) void tp2_allreduce_f16( + global const half *p0, + global const half *p1, + global half *out, + int n4) +{ + const int idx = get_global_id(0); + if (idx >= n4) return; + const float4 s = convert_float4(vload4(idx, p0)) + convert_float4(vload4(idx, p1)); + vstore4(convert_half4_rte(s), idx, out); +} + +// 1-shot P2P AllReduce (FP16): out[i] = fp16_rte(((p0[i] + p1[i]) + p2[i]) + p3[i]) +KERNEL(256) void tp4_allreduce_f16( + global const half *p0, + global const half *p1, + global const half *p2, + global const half *p3, + global half *out, + int n4) +{ + const int idx = get_global_id(0); + if (idx >= n4) return; + float4 s = convert_float4(vload4(idx, p0)) + convert_float4(vload4(idx, p1)); + s = s + convert_float4(vload4(idx, p2)); + s = s + convert_float4(vload4(idx, p3)); + vstore4(convert_half4_rte(s), idx, out); +} + +// 2-shot P2P ReduceScatter (FP16): sums slice [off4 .. off4 + slice_n4) into rs_out[0 .. slice_n4) +KERNEL(256) void tp2_rs_f16( + global const half *p0, + global const half *p1, + global half *rs_out, + int off4, + int slice_n4) +{ + const int idx = get_global_id(0); + if (idx >= slice_n4) return; + const int src = off4 + idx; + const float4 s = convert_float4(vload4(src, p0)) + convert_float4(vload4(src, p1)); + vstore4(convert_half4_rte(s), idx, rs_out); +} + +KERNEL(256) void tp4_rs_f16( + global const half *p0, + global const half *p1, + global const half *p2, + global const half *p3, + global half *rs_out, + int off4, + int slice_n4) +{ + const int idx = get_global_id(0); + if (idx >= slice_n4) return; + const int src = off4 + idx; + float4 s = convert_float4(vload4(src, p0)) + convert_float4(vload4(src, p1)); + s = s + convert_float4(vload4(src, p2)); + s = s + convert_float4(vload4(src, p3)); + vstore4(convert_half4_rte(s), idx, rs_out); +} + +// 1-shot P2P AllReduce (BF16) for BF16/FlashNext activations +KERNEL(256) void tp2_allreduce_bf16( + global const ushort *p0, + global const ushort *p1, + global ushort *out, + int n4) +{ + const int idx = get_global_id(0); + if (idx >= n4) return; + const ushort4 a0 = vload4(idx, p0), a1 = vload4(idx, p1); + ushort4 r; + r.s0 = f2bf(bf2f(a0.s0) + bf2f(a1.s0)); + r.s1 = f2bf(bf2f(a0.s1) + bf2f(a1.s1)); + r.s2 = f2bf(bf2f(a0.s2) + bf2f(a1.s2)); + r.s3 = f2bf(bf2f(a0.s3) + bf2f(a1.s3)); + vstore4(r, idx, out); +} + +KERNEL(256) void tp4_allreduce_bf16( + global const ushort *p0, + global const ushort *p1, + global const ushort *p2, + global const ushort *p3, + global ushort *out, + int n4) +{ + const int idx = get_global_id(0); + if (idx >= n4) return; + const ushort4 a0 = vload4(idx, p0), a1 = vload4(idx, p1), a2 = vload4(idx, p2), a3 = vload4(idx, p3); + ushort4 r; + r.s0 = f2bf(((bf2f(a0.s0) + bf2f(a1.s0)) + bf2f(a2.s0)) + bf2f(a3.s0)); + r.s1 = f2bf(((bf2f(a0.s1) + bf2f(a1.s1)) + bf2f(a2.s1)) + bf2f(a3.s1)); + r.s2 = f2bf(((bf2f(a0.s2) + bf2f(a1.s2)) + bf2f(a2.s2)) + bf2f(a3.s2)); + r.s3 = f2bf(((bf2f(a0.s3) + bf2f(a1.s3)) + bf2f(a2.s3)) + bf2f(a3.s3)); + vstore4(r, idx, out); +} + +// 1-shot P2P AllReduce (FP32) for FlashNext routed MoE / FP32 partials +KERNEL(256) void tp2_allreduce_f32( + global const float *p0, + global const float *p1, + global float *out, + int n4) +{ + const int idx = get_global_id(0); + if (idx >= n4) return; + vstore4(vload4(idx, p0) + vload4(idx, p1), idx, out); +} + +KERNEL(256) void tp4_allreduce_f32( + global const float *p0, + global const float *p1, + global const float *p2, + global const float *p3, + global float *out, + int n4) +{ + const int idx = get_global_id(0); + if (idx >= n4) return; + float4 s = vload4(idx, p0) + vload4(idx, p1); + s = s + vload4(idx, p2); + s = s + vload4(idx, p3); + vstore4(s, idx, out); +} + +KERNEL(256) void tp4_rs_f32( + global const float *p0, + global const float *p1, + global const float *p2, + global const float *p3, + global float *rs_out, + int off4, + int slice_n4) +{ + const int idx = get_global_id(0); + if (idx >= slice_n4) return; + const int src = off4 + idx; + float4 s = vload4(src, p0) + vload4(src, p1); + s = s + vload4(src, p2); + s = s + vload4(src, p3); + vstore4(s, idx, rs_out); +} diff --git a/zig/src/core/contract/xpu_records.zig b/zig/src/core/contract/xpu_records.zig index 50e8107ee3e..086d6536222 100644 --- a/zig/src/core/contract/xpu_records.zig +++ b/zig/src/core/contract/xpu_records.zig @@ -36,6 +36,42 @@ pub const records = [_]Record{ .launch = .{ .name = "embed", .symbol = "embed", .image = "glue", .format = glue, .threads = .{ 256, 1, 1 }, .sub_group = 16, .grf = 256 }, .usage = .{.{ .threads = .{ 256, 1, 1 }, .sub_group = 16, .grf = 256 }}, }, + .{ + .launch = .{ .name = "tp2_allreduce_f16", .symbol = "tp2_allreduce_f16", .image = "tp", .format = glue, .threads = .{ 256, 1, 1 }, .sub_group = 16, .grf = 256 }, + .usage = .{.{ .threads = .{ 256, 1, 1 }, .sub_group = 16, .grf = 256 }}, + }, + .{ + .launch = .{ .name = "tp4_allreduce_f16", .symbol = "tp4_allreduce_f16", .image = "tp", .format = glue, .threads = .{ 256, 1, 1 }, .sub_group = 16, .grf = 256 }, + .usage = .{.{ .threads = .{ 256, 1, 1 }, .sub_group = 16, .grf = 256 }}, + }, + .{ + .launch = .{ .name = "tp2_rs_f16", .symbol = "tp2_rs_f16", .image = "tp", .format = glue, .threads = .{ 256, 1, 1 }, .sub_group = 16, .grf = 256 }, + .usage = .{.{ .threads = .{ 256, 1, 1 }, .sub_group = 16, .grf = 256 }}, + }, + .{ + .launch = .{ .name = "tp4_rs_f16", .symbol = "tp4_rs_f16", .image = "tp", .format = glue, .threads = .{ 256, 1, 1 }, .sub_group = 16, .grf = 256 }, + .usage = .{.{ .threads = .{ 256, 1, 1 }, .sub_group = 16, .grf = 256 }}, + }, + .{ + .launch = .{ .name = "tp2_allreduce_bf16", .symbol = "tp2_allreduce_bf16", .image = "tp", .format = glue, .threads = .{ 256, 1, 1 }, .sub_group = 16, .grf = 256 }, + .usage = .{.{ .threads = .{ 256, 1, 1 }, .sub_group = 16, .grf = 256 }}, + }, + .{ + .launch = .{ .name = "tp4_allreduce_bf16", .symbol = "tp4_allreduce_bf16", .image = "tp", .format = glue, .threads = .{ 256, 1, 1 }, .sub_group = 16, .grf = 256 }, + .usage = .{.{ .threads = .{ 256, 1, 1 }, .sub_group = 16, .grf = 256 }}, + }, + .{ + .launch = .{ .name = "tp2_allreduce_f32", .symbol = "tp2_allreduce_f32", .image = "tp", .format = glue, .threads = .{ 256, 1, 1 }, .sub_group = 16, .grf = 256 }, + .usage = .{.{ .threads = .{ 256, 1, 1 }, .sub_group = 16, .grf = 256 }}, + }, + .{ + .launch = .{ .name = "tp4_allreduce_f32", .symbol = "tp4_allreduce_f32", .image = "tp", .format = glue, .threads = .{ 256, 1, 1 }, .sub_group = 16, .grf = 256 }, + .usage = .{.{ .threads = .{ 256, 1, 1 }, .sub_group = 16, .grf = 256 }}, + }, + .{ + .launch = .{ .name = "tp4_rs_f32", .symbol = "tp4_rs_f32", .image = "tp", .format = glue, .threads = .{ 256, 1, 1 }, .sub_group = 16, .grf = 256 }, + .usage = .{.{ .threads = .{ 256, 1, 1 }, .sub_group = 16, .grf = 256 }}, + }, }; /// Gate 5's planted XPU controls: one for each fit rule the audit must fire. diff --git a/zig/src/families/gemma4/gemma4.zig b/zig/src/families/gemma4/gemma4.zig index 6ad0e3911ec..75b13955841 100644 --- a/zig/src/families/gemma4/gemma4.zig +++ b/zig/src/families/gemma4/gemma4.zig @@ -20,6 +20,7 @@ pub const snapshot = @import("snapshot.zig"); test { _ = backend; + _ = @import("model.zig"); _ = assistant; _ = assistant_weights; _ = config; diff --git a/zig/src/families/gemma4/model.zig b/zig/src/families/gemma4/model.zig index 7246940f2de..d9eeef3b66a 100644 --- a/zig/src/families/gemma4/model.zig +++ b/zig/src/families/gemma4/model.zig @@ -161,12 +161,15 @@ pub const Model = struct { if (m.config.geo.unified()) { try vision_unified.addTensors(&m.checkpoint, m.device, files); if (!vision_unified.present(&m.checkpoint)) return error.NoGemmaVision; - m.vision = .{ .embedder = try vision_unified.Embedder.load(m.gpa, m.device, &m.checkpoint, m.config.geo.hidden, m.pipes(m.config.widths.vision.bits), m.config.widths.vision) }; + // bound first: a failed load must leave m.vision null, not a tag with no embedder behind it + const e = try vision_unified.Embedder.load(m.gpa, m.device, &m.checkpoint, m.config.geo.hidden, m.pipes(m.config.widths.vision.bits), m.config.widths.vision); + m.vision = .{ .embedder = e }; return; } try vision.addTensors(&m.checkpoint, m.device, files); if (!vision.present(&m.checkpoint)) return error.NoGemmaVision; - m.vision = .{ .encoder = try vision.Vision.load(m.gpa, m.device, &m.checkpoint, m.pipes(m.config.widths.vision.bits), m.config.widths.vision, m.config.geo.hidden) }; + const v = try vision.Vision.load(m.gpa, m.device, &m.checkpoint, m.pipes(m.config.widths.vision.bits), m.config.widths.vision, m.config.geo.hidden); + m.vision = .{ .encoder = v }; } /// The drafter's taps, in its feature order: each a layer whose output (layer scalar applied) it reads. @@ -195,3 +198,33 @@ pub const Model = struct { m.gpa.destroy(m); } }; + +test "a tower that fails to load leaves the model without one, so deinit frees nothing that was never made" { + if (comptime !@hasDecl(mtl.Device, "init")) return error.SkipZigTest; + const device = mtl.Device.init() catch return error.SkipZigTest; + defer device.deinit(); + const gpa = std.testing.allocator; + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + // the name vision_unified.present() looks for, so loadVision reaches Embedder.load + const header = + \\{"vision_embedder.patch_dense.weight":{"dtype":"BF16","shape":[2],"data_offsets":[0,4]}} + ; + var data: [8 + header.len + 4]u8 = @splat(0); + std.mem.writeInt(u64, data[0..8], header.len, .little); + @memcpy(data[8..][0..header.len], header); + try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "model.safetensors", .data = &data }); + const dir = try std.fmt.allocPrint(gpa, ".zig-cache/tmp/{s}", .{tmp.sub_path}); + defer gpa.free(dir); + var m: Model = undefined; + m.gpa = gpa; + m.device = device; + m.checkpoint = ckpt.Checkpoint.init(gpa); + defer m.checkpoint.deinit(); + m.vision = null; + m.config = .{ .geo = cfg.unified12b, .context = 1 }; + m.config.geo.hidden = vision_unified.width + 1; // a width the embedder cannot project to: Embedder.load refuses it + for (&m.mm) |*p| p.* = @as(affine_mm.Pipes, undefined); // never read: the refusal comes first + try std.testing.expectError(error.UnexpectedGemmaVisionTensor, m.loadVision(std.testing.io, dir)); + try std.testing.expect(m.vision == null); +} diff --git a/zig/src/families/glm/cuda_follow.zig b/zig/src/families/glm/cuda_follow.zig index 25ef795ed98..11ac9a4053a 100644 --- a/zig/src/families/glm/cuda_follow.zig +++ b/zig/src/families/glm/cuda_follow.zig @@ -154,7 +154,7 @@ pub const Leader = struct { return @intFromBool(x.e.prompt_logprobs != null); } - /// No stream is left: the other ranks sleep on their lines until the next step instead of spinning in NCCL. + /// No stream is left, or rank 0's tower is about to run: the other ranks sleep on their lines until the next step. pub fn idle(x: Leader) !void { if (x.link.asleep or !cuda.tp_watch.open()) return; try x.send(.{ .kind = @backingInt(Kind.idle) }, &.{}); @@ -216,6 +216,13 @@ pub const Leader = struct { try x.send(.{ .kind = @backingInt(Kind.pool), .depth = streams, .a = pages, .seed = page_bytes }, &.{}); } + /// Rank 0's tower encodes the bound slot's images past `from` with the other ranks asleep (#3614), then their rows. + pub fn encode(x: Leader, v: *images_mod.Images, list: []const @import("lanes").stream.Image, from: usize) !void { + try x.idle(); // a net plugin may time out an NCCL wait as long as the pass: they wait on their lines instead + try v.begin(x.e.slot, list, from); // a refusal leaves every rank as it was, asleep until rank 0's next step + try x.images(v); + } + /// The prompt pass's image rows (rank 0 encoded them for the bound slot) to every rank: spans, then the rows. pub fn images(x: Leader, v: *const images_mod.Images) !void { try x.flush(); diff --git a/zig/src/families/glm/cuda_lanes.zig b/zig/src/families/glm/cuda_lanes.zig index 08436c4d045..37eedcc152a 100644 --- a/zig/src/families/glm/cuda_lanes.zig +++ b/zig/src/families/glm/cuda_lanes.zig @@ -360,8 +360,7 @@ pub const Lanes = struct { fn images(self: *Lanes, s: *lanes.Stream, from: ?engine.Resume) !void { if (s.images.len == 0) return; const v = self.x.e.images orelse return error.NoVision; - try v.begin(self.x.e.slot, s.images, if (from) |r| r.at else 0); // a refusal here leaves every rank as it was - try self.x.images(v); + try self.x.encode(v, s.images, if (from) |r| r.at else 0); } const Sink = @import("cuda_prompt_sink.zig").Sink; diff --git a/zig/src/xpu/tp.zig b/zig/src/xpu/tp.zig new file mode 100644 index 00000000000..d339333e9b6 --- /dev/null +++ b/zig/src/xpu/tp.zig @@ -0,0 +1,279 @@ +//! Multi-GPU Level Zero P2P collectives (TP=1, 2, 4) on Intel Xe2 using cross-device events and a 4-slot P2P ring. +const std = @import("std"); +const ze = @import("ze"); + +pub const MAX_TP = 4; +pub const RING_SLOTS = 4; +pub const MAX_PIPE_STEPS = 256; // 64 layers * 2 collectives = 128 steps per forward; 256 leaves ample headroom +/// Threshold above which 2-shot P2P ReduceScatter + DMA AllGather replaces 1-shot P2P AllReduce. +pub const RS_THRESHOLD_BYTES: usize = 512 * 1024; + +pub const Kernels = struct { + ar2_f16: ze.H, + ar4_f16: ze.H, + rs2_f16: ze.H, + rs4_f16: ze.H, + ar2_bf16: ze.H, + ar4_bf16: ze.H, + ar2_f32: ze.H, + ar4_f32: ze.H, + rs4_f32: ze.H, +}; + +pub const TpComm = struct { + tp: usize, + max_bytes: usize, + send_buf: [MAX_TP][RING_SLOTS]*anyopaque = undefined, + rs_buf: [MAX_TP][RING_SLOTS]*anyopaque = undefined, + k: [MAX_TP]Kernels = undefined, + // [step * 2 * MAX_TP + kind * MAX_TP + rank], kind 0 = send ready, kind 1 = rs ready + events: [MAX_PIPE_STEPS * 2 * MAX_TP]ze.H = @splat(null), + step: usize = 0, + + pub fn init(gpus: []ze.Gpu, tp_bin: []const u8, max_bytes: usize) !TpComm { + if (gpus.len != 1 and gpus.len != 2 and gpus.len != 4) return error.InvalidTpDegree; + var c: TpComm = .{ + .tp = gpus.len, + .max_bytes = (max_bytes + 4095) / 4096 * 4096, + }; + if (c.tp == 1) return c; + + const rs_cap = (c.max_bytes / c.tp + 4095) / 4096 * 4096; + for (gpus, 0..) |*g, r| { + for (0..RING_SLOTS) |s| { + c.send_buf[r][s] = try g.deviceAlloc(c.max_bytes); + c.rs_buf[r][s] = try g.deviceAlloc(rs_cap); + } + const m = try g.module(tp_bin); + c.k[r] = .{ + .ar2_f16 = try loadK(g, m, "tp2_allreduce_f16"), + .ar4_f16 = try loadK(g, m, "tp4_allreduce_f16"), + .rs2_f16 = try loadK(g, m, "tp2_rs_f16"), + .rs4_f16 = try loadK(g, m, "tp4_rs_f16"), + .ar2_bf16 = try loadK(g, m, "tp2_allreduce_bf16"), + .ar4_bf16 = try loadK(g, m, "tp4_allreduce_bf16"), + .ar2_f32 = try loadK(g, m, "tp2_allreduce_f32"), + .ar4_f32 = try loadK(g, m, "tp4_allreduce_f32"), + .rs4_f32 = try loadK(g, m, "tp4_rs_f32"), + }; + } + // Make all ring buffers P2P-resident on every peer device in the shared context. + for (gpus) |*g_dst| { + for (0..c.tp) |r_src| { + for (0..RING_SLOTS) |s| { + try g_dst.makeResident(c.send_buf[r_src][s], c.max_bytes); + try g_dst.makeResident(c.rs_buf[r_src][s], rs_cap); + } + } + } + try ze.Gpu.sharedEvents(gpus, c.events[0 .. MAX_PIPE_STEPS * 2 * c.tp]); + return c; + } + + fn loadK(g: *ze.Gpu, m: ze.H, name: [*:0]const u8) !ze.H { + const k = try g.kernel(m, name); + try ze.check(g.api.zeKernelSetGroupSize(k, 256, 1, 1)); + try g.indirect(k); + return k; + } + + /// Rank `r`'s current P2P send buffer so the preceding GEMM can write directly into it without an extra copy. + pub fn currentSendBuf(c: *const TpComm, r: usize) *anyopaque { + return c.send_buf[r][c.step % RING_SLOTS]; + } + + fn readyEv(c: *TpComm, s: usize, r: usize) ze.H { + return c.events[(s * 2 + 0) * c.tp + r]; + } + + fn rsEv(c: *TpComm, s: usize, r: usize) ze.H { + return c.events[(s * 2 + 1) * c.tp + r]; + } + + /// Synchronizes all `gpus` command lists and resets all consumed pipeline events on the host. + pub fn syncAll(c: *TpComm, gpus: []ze.Gpu, lists: []const ze.H) !void { + for (gpus, lists) |*g, l| { + try ze.check(g.api.zeCommandListHostSynchronize(l, std.math.maxInt(u64))); + } + if (c.tp > 1 and c.step > 0) { + const total_evs = c.step * 2 * c.tp; + for (c.events[0..total_evs]) |ev| { + try ze.check(gpus[0].api.zeEventHostReset(ev)); + } + c.step = 0; + } + } + + /// Queues an async cross-GPU FP16 AllReduce from `src_opt` (or `currentSendBuf(r)` if null) into `dst[r]`. + pub fn allReduceF16(c: *TpComm, gpus: []ze.Gpu, lists: []const ze.H, src_opt: ?[]const *anyopaque, dst: []const *anyopaque, count_f16: usize) !void { + if (c.tp == 1) { + if (src_opt) |src| if (src[0] != dst[0]) { + try ze.check(gpus[0].api.zeCommandListAppendMemoryCopy(lists[0], dst[0], src[0], count_f16 * 2, null, 0, null)); + }; + return; + } + if (c.step >= MAX_PIPE_STEPS) try c.syncAll(gpus, lists); + const bytes = count_f16 * 2; + if (bytes > c.max_bytes or count_f16 % 4 != 0) return error.InvalidAllReduceSize; + + const s = c.step; + const slot = s % RING_SLOTS; + c.step += 1; + + var waits: [MAX_TP]ze.H = undefined; + for (0..c.tp) |r| { + const sb = c.send_buf[r][slot]; + if (src_opt) |src| if (src[r] != sb) { + try ze.check(gpus[r].api.zeCommandListAppendMemoryCopy(lists[r], sb, src[r], bytes, null, 0, null)); + }; + const ev = c.readyEv(s, r); + try ze.check(gpus[r].api.zeCommandListAppendSignalEvent(lists[r], ev)); + waits[r] = ev; + } + + const n4: u32 = @intCast(count_f16 / 4); + const use_rs = bytes > RS_THRESHOLD_BYTES and (n4 % @as(u32, @intCast(c.tp)) == 0); + + if (!use_rs) { + const groups: ze.GroupCount = .{ .x = (n4 + 255) / 256 }; + for (0..c.tp) |r| { + const g = &gpus[r]; + if (c.tp == 2) { + const k = c.k[r].ar2_f16; + try g.arg(k, 0, c.send_buf[0][slot]); + try g.arg(k, 1, c.send_buf[1][slot]); + try g.arg(k, 2, dst[r]); + try g.arg(k, 3, @as(i32, @intCast(n4))); + try ze.check(g.api.zeCommandListAppendLaunchKernel(lists[r], k, &groups, null, 2, &waits)); + } else { + const k = c.k[r].ar4_f16; + try g.arg(k, 0, c.send_buf[0][slot]); + try g.arg(k, 1, c.send_buf[1][slot]); + try g.arg(k, 2, c.send_buf[2][slot]); + try g.arg(k, 3, c.send_buf[3][slot]); + try g.arg(k, 4, dst[r]); + try g.arg(k, 5, @as(i32, @intCast(n4))); + try ze.check(g.api.zeCommandListAppendLaunchKernel(lists[r], k, &groups, null, 4, &waits)); + } + } + } else { + const slice_n4: u32 = n4 / @as(u32, @intCast(c.tp)); + const slice_bytes: usize = @as(usize, slice_n4) * 8; + const groups: ze.GroupCount = .{ .x = (slice_n4 + 255) / 256 }; + var rs_waits: [MAX_TP]ze.H = undefined; + for (0..c.tp) |r| { + const g = &gpus[r]; + const off4: i32 = @intCast(@as(u32, @intCast(r)) * slice_n4); + const rev = c.rsEv(s, r); + rs_waits[r] = rev; + if (c.tp == 2) { + const k = c.k[r].rs2_f16; + try g.arg(k, 0, c.send_buf[0][slot]); + try g.arg(k, 1, c.send_buf[1][slot]); + try g.arg(k, 2, c.rs_buf[r][slot]); + try g.arg(k, 3, off4); + try g.arg(k, 4, @as(i32, @intCast(slice_n4))); + try ze.check(g.api.zeCommandListAppendLaunchKernel(lists[r], k, &groups, rev, 2, &waits)); + } else { + const k = c.k[r].rs4_f16; + try g.arg(k, 0, c.send_buf[0][slot]); + try g.arg(k, 1, c.send_buf[1][slot]); + try g.arg(k, 2, c.send_buf[2][slot]); + try g.arg(k, 3, c.send_buf[3][slot]); + try g.arg(k, 4, c.rs_buf[r][slot]); + try g.arg(k, 5, off4); + try g.arg(k, 6, @as(i32, @intCast(slice_n4))); + try ze.check(g.api.zeCommandListAppendLaunchKernel(lists[r], k, &groups, rev, 4, &waits)); + } + } + for (0..c.tp) |r| { + try ze.check(gpus[r].api.zeCommandListAppendWaitOnEvents(lists[r], @intCast(c.tp), &rs_waits)); + for (0..c.tp) |src_r| { + const dst_slice: *anyopaque = @ptrFromInt(@intFromPtr(dst[r]) + src_r * slice_bytes); + try ze.check(gpus[r].api.zeCommandListAppendMemoryCopy(lists[r], dst_slice, c.rs_buf[src_r][slot], slice_bytes, null, 0, null)); + } + } + } + } + + /// Queues an asynchronous cross-GPU deterministic FP32 AllReduce (used by FlashNext / FP32 partials). + pub fn allReduceF32(c: *TpComm, gpus: []ze.Gpu, lists: []const ze.H, src_opt: ?[]const *anyopaque, dst: []const *anyopaque, count_f32: usize) !void { + if (c.tp == 1) { + if (src_opt) |src| if (src[0] != dst[0]) { + try ze.check(gpus[0].api.zeCommandListAppendMemoryCopy(lists[0], dst[0], src[0], count_f32 * 4, null, 0, null)); + }; + return; + } + if (c.step >= MAX_PIPE_STEPS) try c.syncAll(gpus, lists); + const bytes = count_f32 * 4; + if (bytes > c.max_bytes or count_f32 % 4 != 0) return error.InvalidAllReduceSize; + + const s = c.step; + const slot = s % RING_SLOTS; + c.step += 1; + + var waits: [MAX_TP]ze.H = undefined; + for (0..c.tp) |r| { + const sb = c.send_buf[r][slot]; + if (src_opt) |src| if (src[r] != sb) { + try ze.check(gpus[r].api.zeCommandListAppendMemoryCopy(lists[r], sb, src[r], bytes, null, 0, null)); + }; + const ev = c.readyEv(s, r); + try ze.check(gpus[r].api.zeCommandListAppendSignalEvent(lists[r], ev)); + waits[r] = ev; + } + + const n4: u32 = @intCast(count_f32 / 4); + const use_rs = c.tp == 4 and bytes > RS_THRESHOLD_BYTES and (n4 % 4 == 0); + if (!use_rs) { + const groups: ze.GroupCount = .{ .x = (n4 + 255) / 256 }; + for (0..c.tp) |r| { + const g = &gpus[r]; + if (c.tp == 2) { + const k = c.k[r].ar2_f32; + try g.arg(k, 0, c.send_buf[0][slot]); + try g.arg(k, 1, c.send_buf[1][slot]); + try g.arg(k, 2, dst[r]); + try g.arg(k, 3, @as(i32, @intCast(n4))); + try ze.check(g.api.zeCommandListAppendLaunchKernel(lists[r], k, &groups, null, 2, &waits)); + } else { + const k = c.k[r].ar4_f32; + try g.arg(k, 0, c.send_buf[0][slot]); + try g.arg(k, 1, c.send_buf[1][slot]); + try g.arg(k, 2, c.send_buf[2][slot]); + try g.arg(k, 3, c.send_buf[3][slot]); + try g.arg(k, 4, dst[r]); + try g.arg(k, 5, @as(i32, @intCast(n4))); + try ze.check(g.api.zeCommandListAppendLaunchKernel(lists[r], k, &groups, null, 4, &waits)); + } + } + } else { + const slice_n4: u32 = n4 / 4; + const slice_bytes: usize = @as(usize, slice_n4) * 16; + const groups: ze.GroupCount = .{ .x = (slice_n4 + 255) / 256 }; + var rs_waits: [MAX_TP]ze.H = undefined; + for (0..4) |r| { + const g = &gpus[r]; + const off4: i32 = @intCast(@as(u32, @intCast(r)) * slice_n4); + const rev = c.rsEv(s, r); + rs_waits[r] = rev; + const k = c.k[r].rs4_f32; + try g.arg(k, 0, c.send_buf[0][slot]); + try g.arg(k, 1, c.send_buf[1][slot]); + try g.arg(k, 2, c.send_buf[2][slot]); + try g.arg(k, 3, c.send_buf[3][slot]); + try g.arg(k, 4, c.rs_buf[r][slot]); + try g.arg(k, 5, off4); + try g.arg(k, 6, @as(i32, @intCast(slice_n4))); + try ze.check(g.api.zeCommandListAppendLaunchKernel(lists[r], k, &groups, rev, 4, &waits)); + } + for (0..4) |r| { + try ze.check(gpus[r].api.zeCommandListAppendWaitOnEvents(lists[r], 4, &rs_waits)); + for (0..4) |src_r| { + const dst_slice: *anyopaque = @ptrFromInt(@intFromPtr(dst[r]) + src_r * slice_bytes); + try ze.check(gpus[r].api.zeCommandListAppendMemoryCopy(lists[r], dst_slice, c.rs_buf[src_r][slot], slice_bytes, null, 0, null)); + } + } + } + } +}; diff --git a/zig/src/xpu/tp_bench.zig b/zig/src/xpu/tp_bench.zig new file mode 100644 index 00000000000..2b92d04153d --- /dev/null +++ b/zig/src/xpu/tp_bench.zig @@ -0,0 +1,140 @@ +//! Phase 1 benchmark & bit-exactness verification for Level Zero P2P TP=2 and TP=4 collectives on Arc Pro B70. +const std = @import("std"); +const ze = @import("ze"); +const tp_mod = @import("tp.zig"); +const kb = @import("xpu_tp_kernels"); + +fn nowNs() u64 { + var ts: std.c.timespec = undefined; + _ = std.c.clock_gettime(std.c.CLOCK.MONOTONIC, &ts); + return @as(u64, @intCast(ts.sec)) * 1_000_000_000 + @as(u64, @intCast(ts.nsec)); +} + +fn f32ToF16Rte(v: f32) u16 { + const f16_val: f16 = @floatCast(v); + return @bitCast(f16_val); +} + +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| { + std.debug.print("skipped TP={d}: {s}\n", .{ tp_deg, @errorName(err) }); + return; + }; + defer ze.Gpu.closePeers(gpus[0..tp_deg]); + + var lists: [4]ze.H = undefined; + for (0..tp_deg) |r| lists[r] = try gpus[r].immediate(0, 0); + + const max_elems: usize = 4096 * 5120; // up to 4096 rows * 5120 fp16 = 40 MB + const max_bytes: usize = max_elems * 2; + var comm = try tp_mod.TpComm.init(gpus[0..tp_deg], &kb.tp, max_bytes); + + var dsts: [4]*anyopaque = undefined; + for (0..tp_deg) |r| dsts[r] = try gpus[r].deviceAlloc(max_bytes); + + // 1. Strict rank-ordered bit-exactness check (with non-associative float magnitudes!) + { + const test_n: usize = 1024 * 5120; // > 512 KB so we also exercise 2-shot ReduceScatter + AllGather! + var host_in: [4][]u16 = undefined; + for (0..tp_deg) |r| { + host_in[r] = try alloc.alloc(u16, test_n); + var prng = std.Random.DefaultPrng.init(0x12345678 + @as(u64, r) * 99991); + const rnd = prng.random(); + for (host_in[r], 0..) |*x, idx| { + // Inject cancellation/non-associative patterns every 4th element + const f: f16 = switch ((idx + r) % 4) { + 0 => 1024.0, + 1 => -1024.0, + 2 => @floatCast((rnd.float(f32) - 0.5) * 2.0), + else => @floatCast((rnd.float(f32) - 0.5) * 0.01), + }; + x.* = @bitCast(f); + } + } + defer for (0..tp_deg) |r| alloc.free(host_in[r]); + + const ref = try alloc.alloc(u16, test_n); + defer alloc.free(ref); + for (0..test_n) |i| { + var s: f32 = 0.0; + for (0..tp_deg) |r| { + const h: f16 = @bitCast(host_in[r][i]); + s += @as(f32, h); + } + ref[i] = f32ToF16Rte(s); + } + + // Check both small (1-shot, 16384 elems = 32 KB) and large (2-shot RS+AG, test_n = 10 MB) + for ([_]usize{ 16384, test_n }) |cnt| { + for (0..tp_deg) |r| { + const sb = comm.currentSendBuf(r); + try ze.check(gpus[r].api.zeCommandListAppendMemoryCopy(lists[r], sb, host_in[r].ptr, cnt * 2, null, 0, null)); + } + try comm.allReduceF16(gpus[0..tp_deg], lists[0..tp_deg], null, dsts[0..tp_deg], cnt); + try comm.syncAll(gpus[0..tp_deg], lists[0..tp_deg]); + + const got = try alloc.alloc(u16, cnt); + defer alloc.free(got); + for (0..tp_deg) |r| { + try ze.check(gpus[r].api.zeCommandListAppendMemoryCopy(lists[r], got.ptr, dsts[r], cnt * 2, null, 0, null)); + try ze.check(gpus[r].api.zeCommandListHostSynchronize(lists[r], std.math.maxInt(u64))); + for (0..cnt) |i| { + if (got[i] != ref[i]) { + std.debug.print("MISMATCH TP={d} rank={d} cnt={d} idx={d}: got=0x{x} ref=0x{x}\n", .{ tp_deg, r, cnt, i, got[i], ref[i] }); + return error.BitMismatch; + } + } + } + } + std.debug.print("=== TP={d}: bit-exactness PASSED (1-shot 32 KB & 2-shot 10 MB, all {d} ranks == rank-ordered FP32 ref) ===\n", .{ tp_deg, tp_deg }); + } + + // 2. Latency & Bandwidth benchmarks (128 pipelined AllReduces per forward pass = 64 layers * 2) + const cases = [_]struct { label: []const u8, elems: usize, steps: usize, reps: usize }{ + .{ .label = "decode 1 row (10 KB)", .elems = 1 * 5120, .steps = 128, .reps = 20 }, + .{ .label = "verify 8 rows (80 KB)", .elems = 8 * 5120, .steps = 128, .reps = 20 }, + .{ .label = "tree 16 rows (160 KB)", .elems = 16 * 5120, .steps = 128, .reps = 20 }, + .{ .label = "prefill 512r (5.0 MB)", .elems = 512 * 5120, .steps = 16, .reps = 10 }, + .{ .label = "prefill 1024r (10 MB)", .elems = 1024 * 5120, .steps = 16, .reps = 10 }, + .{ .label = "prefill 4096r (40 MB)", .elems = 4096 * 5120, .steps = 8, .reps = 5 }, + }; + + for (cases) |tc| { + // Warmup + for (0..2) |_| { + for (0..tc.steps) |_| { + try comm.allReduceF16(gpus[0..tp_deg], lists[0..tp_deg], null, dsts[0..tp_deg], tc.elems); + } + try comm.syncAll(gpus[0..tp_deg], lists[0..tp_deg]); + } + var best_ns: u64 = std.math.maxInt(u64); + var total_ns: u64 = 0; + for (0..tc.reps) |_| { + const t0 = nowNs(); + for (0..tc.steps) |_| { + try comm.allReduceF16(gpus[0..tp_deg], lists[0..tp_deg], null, dsts[0..tp_deg], tc.elems); + } + try comm.syncAll(gpus[0..tp_deg], lists[0..tp_deg]); + const dt = nowNs() - t0; + if (dt < best_ns) best_ns = dt; + total_ns += dt; + } + const mean_step_us = @as(f64, @floatFromInt(total_ns)) / @as(f64, @floatFromInt(tc.reps * tc.steps)) / 1e3; + const best_step_us = @as(f64, @floatFromInt(best_ns)) / @as(f64, @floatFromInt(tc.steps)) / 1e3; + const bytes = @as(f64, @floatFromInt(tc.elems * 2)); + // Algbw = payload_bytes / time_s; Busbw = algbw * 2 * (tp - 1) / tp + const alg_gbs = bytes / (best_step_us * 1e-6) / 1e9; + const bus_gbs = alg_gbs * 2.0 * @as(f64, @floatFromInt(tp_deg - 1)) / @as(f64, @floatFromInt(tp_deg)); + const per_layer64_ms = best_step_us * 128.0 / 1e3; + std.debug.print(" {s}: best={d:6.2} us/op (mean={d:6.2} us) | 128-op/tok={d:5.2} ms | algbw={d:5.2} GB/s | busbw={d:5.2} GB/s\n", .{ + tc.label, best_step_us, mean_step_us, per_layer64_ms, alg_gbs, bus_gbs, + }); + } +} + +pub fn main() !void { + try runSuite(2); + try runSuite(4); +} diff --git a/zig/src/xpu/ze.zig b/zig/src/xpu/ze.zig index 20698c218f2..c1cb3bbb2dd 100644 --- a/zig/src/xpu/ze.zig +++ b/zig/src/xpu/ze.zig @@ -21,6 +21,11 @@ pub const Api = struct { zeCommandListAppendLaunchKernel: *const fn (H, H, *const GroupCount, H, u32, ?[*]H) callconv(.c) u32, zeCommandListAppendMemoryCopy: *const fn (H, ?*anyopaque, ?*const anyopaque, usize, H, u32, ?[*]H) callconv(.c) u32, zeCommandListAppendBarrier: *const fn (H, H, u32, ?[*]H) callconv(.c) u32, + zeCommandListAppendSignalEvent: *const fn (H, H) callconv(.c) u32, + zeCommandListAppendWaitOnEvents: *const fn (H, u32, [*]H) callconv(.c) u32, + zeCommandListAppendEventReset: *const fn (H, H) callconv(.c) u32, + zeDeviceCanAccessPeer: *const fn (H, H, *u8) callconv(.c) u32, + zeContextMakeMemoryResident: *const fn (H, H, ?*anyopaque, usize) callconv(.c) u32, zeMemAllocDevice: *const fn (H, *const DeviceAllocDesc, usize, usize, H, *?*anyopaque) callconv(.c) u32, zeMemAllocHost: *const fn (H, *const HostAllocDesc, usize, usize, *?*anyopaque) callconv(.c) u32, zeMemFree: *const fn (H, ?*anyopaque) callconv(.c) u32, @@ -204,6 +209,7 @@ pub const Gpu = struct { device: H, context: H, props: DeviceProperties, + shared_ctx: bool = false, // true on non-owning peers opened by openPeers; closePeers releases the group owned: Owned = .{}, // what close() gives back /// Every allocation, kernel, module, list and event made through this Gpu, destroyed by close(). @@ -235,11 +241,34 @@ pub const Gpu = struct { /// Waits for every list this Gpu made, then destroys what it made and the context (startup errors included). pub fn close(g: *Gpu) void { + if (g.shared_ctx) { + _ = releasePeer(&g.api, g.context, &g.owned, false); + return; + } if (release(&g.api, g.context, &g.owned)) g.lib.close(); } + /// Drains all peer command lists first, then frees resources across the group and closes the shared context. + pub fn closePeers(gpus: []Gpu) void { + if (gpus.len == 0) return; + for (gpus) |*g| for (g.owned.lists.items) |l| if (g.api.zeCommandListHostSynchronize(l, std.math.maxInt(u64)) != 0) { + std.log.warn("XPU: a command list did not drain at closePeers; memory and context stay until the process ends", .{}); + return; + }; + var idx = gpus.len; + while (idx > 1) { + idx -= 1; + _ = releasePeer(&gpus[idx].api, gpus[idx].context, &gpus[idx].owned, false); + } + if (releasePeer(&gpus[0].api, gpus[0].context, &gpus[0].owned, true)) gpus[0].lib.close(); + } + /// `close` before the loader: false, with nothing destroyed, when a list does not drain (it may still run). fn release(api: *const Api, context: H, o: *Owned) bool { + return releasePeer(api, context, o, true); + } + + fn releasePeer(api: *const Api, context: H, o: *Owned, destroy_ctx: bool) bool { for (o.lists.items) |l| if (api.zeCommandListHostSynchronize(l, std.math.maxInt(u64)) != 0) { std.log.warn("XPU: a command list did not drain at close; its memory and context stay until the process ends", .{}); return false; @@ -253,11 +282,19 @@ pub const Gpu = struct { while (it.next()) |p| _ = api.zeMemFree(context, @ptrFromInt(p.*)); o.mems.deinit(own_alloc); inline for (.{ &o.kernels, &o.modules, &o.lists, &o.events, &o.pools }) |l| l.deinit(own_alloc); - _ = api.zeContextDestroy(context); + if (destroy_ctx) _ = api.zeContextDestroy(context); return true; } pub fn open(device_id: u32) Error!Gpu { + var out: [1]Gpu = undefined; + try openPeers(device_id, &out); + return out[0]; + } + + /// Opens `out.len` peer-accessible devices of `device_id` on one driver and one shared Level Zero context. + pub fn openPeers(device_id: u32, out: []Gpu) Error!void { + if (out.len == 0 or out.len > 8) return error.NoDevice; var lib = std.DynLib.open("libze_loader.so.1") catch return error.LoaderUnavailable; errdefer lib.close(); const api = try resolve(Api, &lib); @@ -271,22 +308,66 @@ pub const Gpu = struct { if (drv == null) continue; var nv: u32 = 0; // the count first, as context.enumerate (a padded list holds nulls) try check(api.zeDeviceGet(drv, &nv, null)); - var devs: [8]H = @splat(null); + var devs: [16]H = @splat(null); nv = @min(nv, devs.len); try check(api.zeDeviceGet(drv, &nv, &devs)); + var picked: [8]H = @splat(null); + var props: [8]DeviceProperties = @splat(.{}); + var found: usize = 0; for (devs[0..nv]) |dev| { if (dev == null) continue; var p: DeviceProperties = .{}; try check(api.zeDeviceGetProperties(dev, &p)); if (p.deviceId != device_id) continue; - var ctx: H = null; - try check(api.zeContextCreate(drv, &.{}, &ctx)); - return .{ .lib = lib, .api = api, .driver = drv, .device = dev, .context = ctx, .props = p }; + picked[found] = dev; + props[found] = p; + found += 1; + if (found == out.len) break; + } + if (found < out.len) continue; + if (out.len > 1) { + for (0..out.len) |i| for (0..out.len) |j| if (i != j) { + var can: u8 = 0; + try check(api.zeDeviceCanAccessPeer(picked[i], picked[j], &can)); + if (can == 0) return error.ZeFailed; + }; + } + var ctx: H = null; + try check(api.zeContextCreate(drv, &.{}, &ctx)); + for (out, 0..) |*g, i| { + g.* = .{ + .lib = if (i == 0) lib else undefined, + .api = api, + .driver = drv, + .device = picked[i], + .context = ctx, + .props = props[i], + .shared_ctx = i > 0, + }; } + return; } return error.NoDevice; } + pub fn makeResident(g: *Gpu, ptr: *anyopaque, size: usize) Error!void { + try check(g.api.zeContextMakeMemoryResident(g.context, g.device, ptr, size)); + } + + /// Allocates a pool of `count` device-scoped events visible across `gpus` (owned by `gpus[0]`). + pub fn sharedEvents(gpus: []Gpu, out_events: []H) Error!void { + var devs: [8]H = @splat(null); + for (gpus, 0..) |*g, i| devs[i] = g.device; + var pool: H = null; + try check(gpus[0].api.zeEventPoolCreate(gpus[0].context, &.{ .flags = pool_host_visible, .count = @intCast(out_events.len) }, @intCast(gpus.len), &devs, &pool)); + _ = try keep(&gpus[0].owned.pools, pool, gpus[0].api.zeEventPoolDestroy); + for (out_events, 0..) |*e, i| { + // signal=1 (DEVICE), wait=1 (DEVICE): cross-GPU synchronization without host round-trips + try check(gpus[0].api.zeEventCreate(pool, &.{ .index = @intCast(i), .signal = 1, .wait = 1 }, e)); + _ = try keep(&gpus[0].owned.events, e.*, gpus[0].api.zeEventDestroy); + } + } + /// On-board bytes free and in all by Sysman (by UUID); without Sysman (WSL2) both are the core total, less nothing. pub fn memory(g: *Gpu) Error!struct { free: u64, size: u64 } { if (!sysmanUsable()) { diff --git a/zig/tests/xpu/contract_live.zig b/zig/tests/xpu/contract_live.zig index 4d648bc00a3..513edd48a32 100644 --- a/zig/tests/xpu/contract_live.zig +++ b/zig/tests/xpu/contract_live.zig @@ -12,6 +12,7 @@ fn isControl(r: records.Record) bool { fn imageOf(name: []const u8) ?rig_.Image { if (std.mem.eql(u8, name, "glue")) return .glue; + if (std.mem.eql(u8, name, "tp")) return .tp; if (std.mem.eql(u8, name, "contract_controls")) return .controls; return null; } @@ -25,6 +26,15 @@ fn argsOf(symbol: []const u8) u32 { .{ "swiglu", 7 }, .{ "argmax", 3 }, .{ "embed", 6 }, + .{ "tp2_allreduce_f16", 4 }, + .{ "tp4_allreduce_f16", 6 }, + .{ "tp2_rs_f16", 5 }, + .{ "tp4_rs_f16", 7 }, + .{ "tp2_allreduce_bf16", 4 }, + .{ "tp4_allreduce_bf16", 6 }, + .{ "tp2_allreduce_f32", 4 }, + .{ "tp4_allreduce_f32", 6 }, + .{ "tp4_rs_f32", 7 }, }; for (table) |e| if (std.mem.eql(u8, e[0], symbol)) return e[1]; return 1; // gate 5's controls take one output pointer diff --git a/zig/tests/xpu/contract_rig.zig b/zig/tests/xpu/contract_rig.zig index 922fd756539..939daef61b2 100644 --- a/zig/tests/xpu/contract_rig.zig +++ b/zig/tests/xpu/contract_rig.zig @@ -8,23 +8,25 @@ const images = @import("xpu_contract_images"); pub const guard = 256; const pattern = 0xa5; -/// The image a kernel lives in: the Qwen3.8-27B glue, gate 5's controls, or gates 1 to 4's. -pub const Image = enum { glue, controls, gate }; +/// The image a kernel lives in: the Qwen3.8-27B glue, TP collectives, gate 5's controls, or gates 1 to 4's. +pub const Image = enum { glue, tp, controls, gate }; fn blob(i: Image) []const u8 { return switch (i) { .glue => &images.glue, + .tp => &images.tp, .controls => &images.controls, .gate => &images.gate_controls, }; } -/// One card, its context and stream, and the three images loaded native for it. +/// One card, its context and stream, and the contract images loaded native for it. pub const Dev = struct { drv: xpu.Driver, ctx: xpu.Context, s: xpu.Stream, glue: xpu.Module, + tp: xpu.Module, controls: ?xpu.Module, // the driver refuses the whole image when one control asks for more SLM than it has controls_err: ?anyerror = null, gate: xpu.Module, @@ -35,6 +37,7 @@ pub const Dev = struct { self.ctx = try xpu.Context.init(&self.drv, ordinal); self.s = try xpu.Stream.init(&self.ctx); self.glue = try xpu.Module.loadNative(&self.ctx, blob(.glue)); + self.tp = try xpu.Module.loadNative(&self.ctx, blob(.tp)); self.controls = xpu.Module.loadNative(&self.ctx, blob(.controls)) catch |e| blk: { self.controls_err = e; break :blk null; @@ -45,6 +48,7 @@ pub const Dev = struct { pub fn deinit(self: *Dev) void { self.gate.unload(); if (self.controls) |*m| m.unload(); + self.tp.unload(); self.glue.unload(); self.s.deinit(); self.ctx.deinit(); @@ -54,6 +58,7 @@ pub const Dev = struct { pub fn module(self: *Dev, i: Image) !*xpu.Module { return switch (i) { .glue => &self.glue, + .tp => &self.tp, .controls => if (self.controls) |*m| m else error.ControlsNotBuilt, .gate => &self.gate, }; diff --git a/zig/tests/xpu/contract_run.zig b/zig/tests/xpu/contract_run.zig index 28c5d96e8ef..d797a213e44 100644 --- a/zig/tests/xpu/contract_run.zig +++ b/zig/tests/xpu/contract_run.zig @@ -8,6 +8,7 @@ const norm_k = @import("contract_norm.zig"); const swiglu_k = @import("contract_swiglu.zig"); const argmax_k = @import("contract_argmax.zig"); const embed_k = @import("contract_embed.zig"); +const tp_k = @import("contract_tp.zig"); const controls_k = @import("contract_controls.zig"); const g = core.gates; @@ -51,6 +52,10 @@ pub fn main(init: std.process.Init) !u8 { var embed = try embed_k.Embed.init(a, &dev); defer embed.deinit(); try kernels.append(a, embed.kernel()); + var tps: [std.enums.values(tp_k.Which).len]tp_k.Tp = undefined; + for (&tps, std.enums.values(tp_k.Which)) |*x, w| x.* = try tp_k.Tp.init(a, &dev, w); + defer for (&tps) |*x| x.deinit(); + for (&tps) |*x| try kernels.append(a, x.kernel()); var controls: [std.enums.values(controls_k.Which).len]controls_k.Control = undefined; for (&controls, std.enums.values(controls_k.Which)) |*x, w| x.* = try controls_k.Control.init(a, &dev, w); defer for (&controls) |*x| x.deinit(); diff --git a/zig/tests/xpu/contract_tp.zig b/zig/tests/xpu/contract_tp.zig new file mode 100644 index 00000000000..cbf9f44f18d --- /dev/null +++ b/zig/tests/xpu/contract_tp.zig @@ -0,0 +1,215 @@ +//! Level Zero TP={2,4} collective kernels in tp.cl under the XPU kernel contract (gates 1 to 4). +const std = @import("std"); +const xpu = @import("xpu"); +const core = @import("core"); +const rig_ = @import("contract_rig.zig"); +const kit = @import("contract_kit.zig"); + +const c = core.spec; +const g = core.gates; +const rows = core.rows; + +/// All nine P2P collective kernels in zig/kernels/xpu/tp.cl. +pub const Which = enum { ar2_f16, ar4_f16, rs2_f16, rs4_f16, ar2_bf16, ar4_bf16, ar2_f32, ar4_f32, rs4_f32 }; + +const why_k2_f16 = "two fp16 inputs sum once directly to fp16 without an intermediate narrowing loss"; +const why_k2_bf16 = "two bf16 inputs sum once directly to bf16, while fp16 sums overflow at 65536"; + +fn symbol(w: Which) []const u8 { + return switch (w) { + .ar2_f16 => "tp2_allreduce_f16", + .ar4_f16 => "tp4_allreduce_f16", + .rs2_f16 => "tp2_rs_f16", + .rs4_f16 => "tp4_rs_f16", + .ar2_bf16 => "tp2_allreduce_bf16", + .ar4_bf16 => "tp4_allreduce_bf16", + .ar2_f32 => "tp2_allreduce_f32", + .ar4_f32 => "tp4_allreduce_f32", + .rs4_f32 => "tp4_rs_f32", + }; +} + +fn ranksOf(w: Which) usize { + return switch (w) { + .ar2_f16, .rs2_f16, .ar2_bf16, .ar2_f32 => 2, + else => 4, + }; +} + +fn kindOf(w: Which) kit.Kind { + return switch (w) { + .ar2_f16, .ar4_f16, .rs2_f16, .rs4_f16 => .f16, + .ar2_bf16, .ar4_bf16 => .bf16, + .ar2_f32, .ar4_f32, .rs4_f32 => .f32, + }; +} + +fn isRs(w: Which) bool { + return w == .rs2_f16 or w == .rs4_f16 or w == .rs4_f32; +} + +fn depth2(_: c.Shape) usize { + return 1; +} + +fn depth4(_: c.Shape) usize { + return 3; +} + +const served2 = [_]c.Shape{ + .{ .rows = 1, .n = 4, .k = 2 }, + .{ .rows = 1, .n = 1024, .k = 2 }, + .{ .rows = 1, .n = 4096, .k = 2 }, +}; + +const served4 = [_]c.Shape{ + .{ .rows = 1, .n = 4, .k = 4 }, + .{ .rows = 1, .n = 1024, .k = 4 }, + .{ .rows = 1, .n = 4096, .k = 4 }, +}; + +pub fn spec(w: Which) c.Spec { + const tp = ranksOf(w); + const kind = kindOf(w); + const sums: c.Sums = switch (w) { + .ar2_f16, .rs2_f16 => .{ .f16 = 0, .bf16 = 0, .why = why_k2_f16 }, + .ar2_bf16 => .{ .bf16 = 0, .why = why_k2_bf16 }, + else => .{}, + }; + return .{ + .name = symbol(w), + .accum = .f32, + .depth = if (tp == 2) depth2 else depth4, + .out = kit.elem(kind), + .tiles = .{ .{}, .{ .size = 1024, .step = 4, .min = 4 }, .{} }, + .served = if (tp == 2) &served2 else &served4, + .sums = sums, + }; +} + +/// Device buffers and host reference inputs for one tp.cl collective kernel. +pub const Tp = struct { + rig: rig_.Rig, + k: xpu.Kernel, + which: Which, + arena: std.heap.ArenaAllocator, + shape: c.Shape = undefined, + inputs: [4][]f64 = .{ &.{}, &.{}, &.{}, &.{} }, + devs: [4]?*anyopaque = .{ null, null, null, null }, + out: ?*anyopaque = null, + slice_off: usize = 0, + + pub fn init(a: std.mem.Allocator, dev: *rig_.Dev, which: Which) !Tp { + return .{ .rig = .{ .a = a, .dev = dev }, .k = try dev.kernelFor(.tp, symbol(which), a), .which = which, .arena = .init(a) }; + } + + pub fn deinit(self: *Tp) void { + self.k.deinit(); + self.arena.deinit(); + self.rig.deinit(); + } + + pub fn kernel(self: *Tp) g.Kernel { + return .{ .spec = spec(self.which), .ctx = self, .vt = &vt }; + } + + const vt = g.hooks(Tp); + + fn stressVals(w: Which) [4]f64 { + return switch (w) { + .ar2_f16, .rs2_f16 => .{ 4096, 16, 0, 0 }, + .ar2_bf16 => .{ 65536, 512, 0, 0 }, + .ar2_f32 => .{ 1048576, 4096, 0, 0 }, + .ar4_f16, .rs4_f16 => .{ 40000, 40000, -40000, -39936 }, + .ar4_bf16 => .{ 131072, 256, -131072, 0 }, + .ar4_f32, .rs4_f32 => .{ 1048576, 4096, -1048576, 0 }, + }; + } + + pub fn prepare(self: *Tp, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + const tp = ranksOf(self.which); + if (shape.rows == 0 or shape.n == 0 or shape.n % 4 != 0 or shape.k != tp) return false; + self.rig.reset(); + _ = self.arena.reset(.retain_capacity); + self.shape = shape; + const a = self.arena.allocator(); + const kind = kindOf(self.which); + const total = shape.rows * shape.n; + const full_n = if (isRs(self.which)) tp * total else total; + self.slice_off = if (isRs(self.which)) total else 0; + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + for (0..tp) |r| { + self.inputs[r] = try a.alloc(f64, full_n); + if (fill == .stress) { + const sv = stressVals(self.which)[r]; + for (self.inputs[r]) |*v| v.* = kit.round(kind, sv); + } else { + for (self.inputs[r]) |*v| v.* = kit.round(kind, -4 + rng.float(f64) * 8); + } + } + if (fill == .nonfinite) { + const off = self.slice_off; + self.inputs[0][off] = std.math.nan(f64); + if (shape.rows > 1) self.inputs[1 % tp][off + shape.n] = std.math.inf(f64); + if (shape.rows > 2) self.inputs[0][off + 2 * shape.n] = -std.math.inf(f64); + if (shape.rows > 3) { + self.inputs[1 % tp][off + 3 * shape.n] = std.math.inf(f64); + self.inputs[0][off + 3 * shape.n] = -std.math.inf(f64); + } + } + for (0..tp) |r| { + const b = try kit.bytes(a, self.inputs[r], kind); + self.devs[r] = try self.rig.input(b); + } + self.out = try self.rig.output(total * kit.size(kind)); + return true; + } + + pub fn run(self: *Tp) !void { + const n4: i32 = @intCast((self.shape.rows * self.shape.n) / 4); + const off4: i32 = @intCast(self.slice_off / 4); + const groups: [3]u32 = .{ @intCast((@as(usize, @intCast(n4)) + 255) / 256), 1, 1 }; + const tp = ranksOf(self.which); + if (isRs(self.which)) { + if (tp == 2) { + try self.rig.launch(self.k, groups, .{ self.devs[0], self.devs[1], self.out, off4, n4 }); + } else { + try self.rig.launch(self.k, groups, .{ self.devs[0], self.devs[1], self.devs[2], self.devs[3], self.out, off4, n4 }); + } + } else if (tp == 2) { + try self.rig.launch(self.k, groups, .{ self.devs[0], self.devs[1], self.out, n4 }); + } else { + try self.rig.launch(self.k, groups, .{ self.devs[0], self.devs[1], self.devs[2], self.devs[3], self.out, n4 }); + } + } + + pub fn count(self: *Tp) usize { + return self.shape.rows * self.shape.n; + } + + pub fn reference(self: *Tp, want: []f64, mag: []f64) !void { + const tp = ranksOf(self.which); + const kind = kindOf(self.which); + for (0..self.count()) |i| { + var s: f64 = 0; + var abs: f64 = 0; + for (0..tp) |r| { + const v = self.inputs[r][self.slice_off + i]; + s += v; + abs += @abs(v); + } + want[i] = kit.round(kind, s); + mag[i] = abs; + } + } + + pub fn simulate(self: *Tp, acc: c.Accum, order: g.Order, out: []f64) !void { + const tp = ranksOf(self.which); + var terms: [4]f64 = undefined; + for (0..self.count()) |i| { + for (0..tp) |r| terms[r] = self.inputs[r][self.slice_off + i]; + out[i] = rows.sumIn(acc, order, terms[0..tp]); + } + } +};